Accueil > > > ENCODAGE UTF16
ENCODAGE UTF16
Information sur la source
Description
PHP supporte mal les caractères supérieurs à 1 octets. J'ai trouvé plusieurs sources (ou fonctions de PHP) pour contourner certains problèmes mais aucune ne me convenait réellement. Tout feedback est bienvenue. :)
Source
- <?php
- /**
- * This File is part of APIS Framework.
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation, either version 3 of the License.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- * See the GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- *
- * @category APIS Tools
- * @package None
- * @copyright Copyright (c) 2009-2010 APIS ( VAT ID: FR74 510 367 881 000 16 )
- * @author Salvan Gregory <apis@apieum.com> <+33 (0) 810 200 119>
- * @license http://www.gnu.org/licenses/gpl.txt GPL3
- * @rev 5
- */
-
- /**
- * @param int $int UTF-16 Char Code
- * @return string the corresponding char hexadecimal value in UTF-8
- * @example for UTF-16:0x4E00 return "\\xE4\\xB8\\x80"
- */
- function strval16( $int ) {
- if ($int<0x80) {
- return '\\x'.dechex($int);
- } elseif ($int<0x110000) {
- $bin = strrev(decbin($int));
- $c = strlen($bin);
- if ($int>0x7FF) {
- if($int<0x10000) {
- if ($c<13)$bin.=str_repeat('0',13-$c);
- } elseif($c<19) {
- $bin.=str_repeat('0',19-$c);
- }
- }
- $str = str_split($bin,6);
- for ($i=0;$i<count($str)-1;$i++) {
- $str[$i]='\\x'.base_convert('10'.strrev($str[$i]),2,16);
- }
- $c = 8-(strlen($str[$i])+$i+1);
- $str[$i]=str_repeat('1',$i+1).str_repeat('0',$c).strrev($str[$i]);
- $str[$i]='\\x'.base_convert($str[$i],2,16);
- $str = array_reverse($str);
- return implode('',$str);
- } else {
- throw new OutOfRangeException("UTF16 accept Chars codes under 0x10FFFF");
- }
- }
-
- /**
- * @param int $int UTF-16 Char Code
- * @return string the corresponding char encoded in UTF-8
- * @example for UTF-16:0x4E00 return UTF-8:0xE4 0xB8 0x80 ("\xE4\xB8\x80")
- * @link http://www.ietf.org/rfc/rfc3629.txt See UTF-8 definition for more informations
- */
- function chr16to8( $int ) {
- if ($int<0x80) {
- return chr($int);
- } elseif ($int<0x110000) {
- $bin = strrev(decbin($int));
- $c = strlen($bin);
- if ($int>0x7FF) {
- if($int<0x10000) {
- if($c<13)$bin.=str_repeat('0',13-$c);
- } elseif($c<19){
- $bin.=str_repeat('0',19-$c);
- }
- }
- $str = str_split($bin,6);
- for ($i=0;$i<count($str)-1;$i++) {
- $str[$i]=chr(base_convert('10'.strrev($str[$i]),2,10));
- }
- $c = 8-(strlen($str[$i])+$i+1);
- $str[$i]=str_repeat('1',$i+1).str_repeat('0',$c).strrev($str[$i]);
- $str[$i]=chr(base_convert($str[$i],2,10));
- $str = array_reverse($str);
- return implode('',$str);
- } else {
- throw new OutOfRangeException("UTF16 accept Chars codes under 0x10FFFF");
- }
- }
- /**
- * @param string $str Text which contains UTF-16 Characters (Raw)
- * @return string $str with UTF-16 characters into html entities
- */
- function html_entity_encode16( $str) {
- // Chars between 0xD800 and 0xDFFF aren't found
- if (preg_match_all('@[\x{80}-\x{10FFFF}]@u',$str,$res)!=false) {
- $res = array_unique($res[0]);
- foreach($res as $k=>$v) {
- $v = str_split(bin2hex($v),2);
- $c = count($v)-1;
- for ($i=$c;$i>0;$i--) {
- $v[$i]=substr(base_convert($v[$i],16,2),-6);
- }
- $v[0]=substr(base_convert($v[0],16,2),$c-6);
- $res1[$k]= '&#'.base_convert(implode('',$v),2,10).';';
- }
- return str_replace($res,$res1,$str);
- }
- return $str;
- }
- /**
- * @param string $str Text which contains html characters entities
- * @return string $str with UTF-16 raw characters.
- */
- function html_entity_decode16( $str) {
- if (preg_match_all('@&#[0-9a-f]+;@i',$str,$res)!=false) {
- $res = array_unique($res[0]);
- foreach($res as $k=>$v) {
- $res1[$k]=chr16to8(intval(substr($v,2,strlen($v)-1)));
- }
- return str_replace($res,$res1,$str);
- }
- return $str;
- }
<?php
/**
* This File is part of APIS Framework.
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* @category APIS Tools
* @package None
* @copyright Copyright (c) 2009-2010 APIS ( VAT ID: FR74 510 367 881 000 16 )
* @author Salvan Gregory <apis@apieum.com> <+33 (0) 810 200 119>
* @license http://www.gnu.org/licenses/gpl.txt GPL3
* @rev 5
*/
/**
* @param int $int UTF-16 Char Code
* @return string the corresponding char hexadecimal value in UTF-8
* @example for UTF-16:0x4E00 return "\\xE4\\xB8\\x80"
*/
function strval16( $int ) {
if ($int<0x80) {
return '\\x'.dechex($int);
} elseif ($int<0x110000) {
$bin = strrev(decbin($int));
$c = strlen($bin);
if ($int>0x7FF) {
if($int<0x10000) {
if ($c<13)$bin.=str_repeat('0',13-$c);
} elseif($c<19) {
$bin.=str_repeat('0',19-$c);
}
}
$str = str_split($bin,6);
for ($i=0;$i<count($str)-1;$i++) {
$str[$i]='\\x'.base_convert('10'.strrev($str[$i]),2,16);
}
$c = 8-(strlen($str[$i])+$i+1);
$str[$i]=str_repeat('1',$i+1).str_repeat('0',$c).strrev($str[$i]);
$str[$i]='\\x'.base_convert($str[$i],2,16);
$str = array_reverse($str);
return implode('',$str);
} else {
throw new OutOfRangeException("UTF16 accept Chars codes under 0x10FFFF");
}
}
/**
* @param int $int UTF-16 Char Code
* @return string the corresponding char encoded in UTF-8
* @example for UTF-16:0x4E00 return UTF-8:0xE4 0xB8 0x80 ("\xE4\xB8\x80")
* @link http://www.ietf.org/rfc/rfc3629.txt See UTF-8 definition for more informations
*/
function chr16to8( $int ) {
if ($int<0x80) {
return chr($int);
} elseif ($int<0x110000) {
$bin = strrev(decbin($int));
$c = strlen($bin);
if ($int>0x7FF) {
if($int<0x10000) {
if($c<13)$bin.=str_repeat('0',13-$c);
} elseif($c<19){
$bin.=str_repeat('0',19-$c);
}
}
$str = str_split($bin,6);
for ($i=0;$i<count($str)-1;$i++) {
$str[$i]=chr(base_convert('10'.strrev($str[$i]),2,10));
}
$c = 8-(strlen($str[$i])+$i+1);
$str[$i]=str_repeat('1',$i+1).str_repeat('0',$c).strrev($str[$i]);
$str[$i]=chr(base_convert($str[$i],2,10));
$str = array_reverse($str);
return implode('',$str);
} else {
throw new OutOfRangeException("UTF16 accept Chars codes under 0x10FFFF");
}
}
/**
* @param string $str Text which contains UTF-16 Characters (Raw)
* @return string $str with UTF-16 characters into html entities
*/
function html_entity_encode16( $str) {
// Chars between 0xD800 and 0xDFFF aren't found
if (preg_match_all('@[\x{80}-\x{10FFFF}]@u',$str,$res)!=false) {
$res = array_unique($res[0]);
foreach($res as $k=>$v) {
$v = str_split(bin2hex($v),2);
$c = count($v)-1;
for ($i=$c;$i>0;$i--) {
$v[$i]=substr(base_convert($v[$i],16,2),-6);
}
$v[0]=substr(base_convert($v[0],16,2),$c-6);
$res1[$k]= '&#'.base_convert(implode('',$v),2,10).';';
}
return str_replace($res,$res1,$str);
}
return $str;
}
/**
* @param string $str Text which contains html characters entities
* @return string $str with UTF-16 raw characters.
*/
function html_entity_decode16( $str) {
if (preg_match_all('@&#[0-9a-f]+;@i',$str,$res)!=false) {
$res = array_unique($res[0]);
foreach($res as $k=>$v) {
$res1[$k]=chr16to8(intval(substr($v,2,strlen($v)-1)));
}
return str_replace($res,$res1,$str);
}
return $str;
}
Conclusion
Ce code permet d'afficher en UTF-8 les caractères supérieurs à 1 octets mais aussi de les protéger pour les afficher dans une page web. Il se compose de 4 fonctions : * strval16 qui retourne la séquence de valeurs hexadécimales représentant un caractère UTF-16 convertit en UTF-8. * chr16to8 qui retourne un caractère UTF8 à partir de son code UTF-16 (en hexa ou décimal jusqu'à 0x0010FFFF [4o] ) * html_entity_encode16 qui remplace les caractères UTF-16 d'une chaine par l'entité de caractère HTLM correspondante. * html_entity_decode16 qui remplace les entités de caractères HTML par le caractère UTF-16 correspondant. Le ZIP contient en plus les tests unitaires (basiques) dont le résultat est ci-joint en capture.
Historique
- 29 mars 2010 02:30:38 :
- Ajout d'une fonction, ajout d'un test
Sources de la même categorie
RÉCUPÉRER LES MINIATURES D'UNE VIDÉO YOUTUBERÉCUPÉRER LES MINIATURES D'UNE VIDÉO YOUTUBE Le code est simple, il permet depuis une url youtube de récupérer son identifiant et de se connecter au serveur de miniatures pour en récupérer les im...
par tefa24600
CONVERTISSEUR DE NOMBRES EN TEXTECONVERTISSEUR DE NOMBRES EN TEXTEQu'est-ce ? Un convertisseur de nombre en texte.
Ses particularités?
- pas de limitation sur la taille du nombre (traitement en string, et non en ...
par macruz
CODAGE TEXTE >HTML, ISO, SPECIALCHARS, URL ET DECODAGECODAGE TEXTE >HTML, ISO, SPECIALCHARS, URL ET DECODAGECe script php permet, comme son nom l'indique de coder un texte pour remplacer les caractères spéciaux, ou apprendre à comprendre les htmlentities, sp...
par Salva9473
Commentaires et avis
Discussions en rapport avec ce code source dans le forum
Traduction de chaines de caractères [ par bito yep ]
Bonjour, Pour mon site, je voudrais savoir si il etait possible dans une chaine de caractères de remplacer ^001234 (ou n'importe quels chiffres en héx
menu et chaines de caractères [ par ayor ]
bien le bonjour à tous, je voulais juste poser 2 petites questions : - tout d'abord, sous phpmyadmin, est-il possible de créer des champs de text
SQL server & encodage caractères [ par ljanvier ]
Bonjour, J'utilise PHP+apache+MS SQL server. Avec ce trio, quand je fais des requêtes sur ma base de donnée, j'obtiens des erreurs d'encodag
Récupérer des chaines de caractères [ par gaspard83 ]
Bonjour à tous, Je voulais savoir si il existait un script php qui permet de récupérer les chaines de caractères (le texte des pa
Caractères spéciaux, url et encodage [ par bigflo ]
Salut,Voici mon problème, en php, je fais un listing d'un répertoire. J'affiche donc par moment des liens vers des fichiers. mais lorsque le nom du fi
textaera [ par qazar ]
bonjourcomment limiter le nombres de caractères ou de lignes (il me faut plus de 255 caract) dans un textaera sachant que la valeur sera inscite dans
Chaine de caractères [ par stailer ]
Bonjour,J'ai une chaine de caractère dans une variable qui se finit toujours par une virgule... c'est voulu.Mais y a un moment ou j'aimerais l'enlever
chaine de caractères [ par jerame ]
Bonjour,Quand on utilise du code php, le plus dur, c'est de jongler avec le code html.J'ai vu qu'il y'avait peut être une solution pour mettre tout le
Caractères accentués avec ImageTTFText ? [ par bibos ]
Bonjour,Je viens de me mettre à la génération d'images en PHP, et j'ai un premier problème sur lequel je bute depuis 24h...Et ça me parait tellement b
Pb d'enregistrement dans ma base [ par lineb76 ]
Lorsque je veux enregistrer des données dans ma table il me rajoute, à la place des caractères accentués par exemple, des caractères bizarre du style
|
Derniers Blogs
IMAGINE CUP 2012, MAKE A SIGN EN FINALEIMAGINE CUP 2012, MAKE A SIGN EN FINALE par junarnoalg
Voilà qui est fait, la nouvelle est officielle ! L'équipe belge "Make a Sign" va au pays des kangourous défendre son projet dans la catégorie Software Design. http://www.imaginecup.com/CompetitionsContent/Competition/WorldwideFinalists.aspx V...
Cliquez pour lire la suite de l'article par junarnoalg KINECT 1.5 IS OUT !KINECT 1.5 IS OUT ! par Vko
La version 1.5 du Kinect For Microsoft vient tout juste de sortir ! Plein de nouveautés: Tracking de squelette en Near Mode Détection en position assise Détection faciale avec un SDK dédié Documentation et des guideline (enfin) Un out...
Cliquez pour lire la suite de l'article par Vko LES ACTUALITéS DE LA SEMAINE SUR C2I.FR (14 MAI - 20 MAI) LES ACTUALITéS DE LA SEMAINE SUR C2I.FR (14 MAI - 20 MAI) par richardc
Mise à jour des Web API du 14 Mai
Réservez dès maintenant votre journée du 20 juin pour le Windows Azure Dev Camp 2012 à Paris
Mise à jour de Team Foundation Service
MechCommander 2 sur Windows 8
Entity Framework 5 Release Candidate e...
Cliquez pour lire la suite de l'article par richardc REACTIVE EXTENSIONS : CONSOMMER DES SERVICES AVEC RX PARTIE 3, LES PIèGES à éVITERREACTIVE EXTENSIONS : CONSOMMER DES SERVICES AVEC RX PARTIE 3, LES PIèGES à éVITER par Groc
Une mauvaise utilisation de rx lors de l'écriture d'une couche d'accès à des services peut conduire à des cas embarassants avec des erreurs mal gérées, des appels qui ne partent lorsqu'ils le devraient, et même des résultats incorrects . le tout nuis...
Cliquez pour lire la suite de l'article par Groc SHAREPOINT BLOG SITE, PROBLèME D'ARCHIVESSHAREPOINT BLOG SITE, PROBLèME D'ARCHIVES par junarnoalg
Dernièrement, nous avons migré le site
myTIC
vers un nouveau serveur SharePoint 2010. Dans les contenus que nous vouloins récupérer, nous avions un certain nombre de blogs.
Nous avons utilisé les commandes Power...
Cliquez pour lire la suite de l'article par junarnoalg
Logiciels
sDEVIS-FACTURES vlPRO (8.1.0.3)SDEVIS-FACTURES VLPRO (8.1.0.3)sDEVIS-FACTURES vlPRO a été mis au point pour les particuliers, créateurs, entrepreneurs, artisa... Cliquez pour télécharger sDEVIS-FACTURES vlPRO 974 Application Server (12.2.4.6)974 APPLICATION SERVER (12.2.4.6)Développez de puissantes applications dans un environnement de 'cloud computing', clusterisé, séc... Cliquez pour télécharger 974 Application Server vPicture (1.4.2.1)VPICTURE (1.4.2.1)Avec vPicture, hébergez vos images facilement et rapidement.
vPicture est un utilitaire simple, ... Cliquez pour télécharger vPicture Easy-Planning (2.2.1.6)EASY-PLANNING (2.2.1.6)Easy-Planning permet de créer des plannings sous la représentation de diagrammes et est adapté au... Cliquez pour télécharger Easy-Planning COM-BACKUP (2.0)COM-BACKUP (2.0)
COM-BACKUP est un logiciel de sauvegarde qui permet de planifier les sauvegardes de vos dossiers ...
Cliquez pour télécharger COM-BACKUP
|