begin process at 2012 05 27 20:02:33
  Trouver un code source :
 
dans
 
Accueil > 

Code

 > 

Chaîne de caratère

 > ENCODAGE UTF16

ENCODAGE UTF16


 Information sur la source

Note :
Aucune note
Catégorie :Chaîne de caratère Classé sous :encodage, chaines, caractères Niveau :Initié Date de création :26/03/2010 Date de mise à jour :29/03/2010 02:30:32 Vu / téléchargé :3 162 / 58

Auteur : foisse

Ecrire un message privé
Commentaire sur cette source (0)
Ajouter un commentaire et/ou une note

 Description

Cliquez pour voir la capture en taille normale
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.

 Fichier Zip

Les Membres Club peuvent télécharger directement un fichier contenu dans le zip sans télécharger le zip en entier !

Télécharger le zip


 Historique

29 mars 2010 02:30:38 :
Ajout d'une fonction, ajout d'un test

 Sources de la même categorie

ADRESSE ABSOLUE DE LA PAGE EN COURS, AVEC VARIABLES $_GET par Dariumis
Source avec Zip CLASSE D'OBJET DE RECHERCHE DE MOTS DANS DES TABLEAUX ET/OU ... par 8Tnerolf8
RÉCUPÉRER LES MINIATURES D'UNE VIDÉO YOUTUBE par tefa24600
Source avec Zip Source avec une capture CONVERTISSEUR DE NOMBRES EN TEXTE par macruz
Source avec Zip Source avec une capture CODAGE TEXTE >HTML, ISO, SPECIALCHARS, URL ET DECODAGE par Salva9473

 Sources en rapport avec celle ci

CRÉER UN PARSEUR LL par Morphinof
Source avec Zip Source avec une capture CODAGE TEXTE >HTML, ISO, SPECIALCHARS, URL ET DECODAGE par Salva9473
GÉNÉRER UNE CHAÎNE ALÉATOIRE SANS BOUCLE NI CRYPTAGE (MD5 OU... par kylekatarnls
CLASSE FFMPEG DE GESTION DE VIDÉOS par Yaug
CONVERSION DES CARACTÈRES SPÉCIAUX DANS UNE BASE DE DONNÉES ... par crocblanc

Commentaires et avis

Aucun commentaire pour le moment.

 Ajouter un commentaire


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&#234;tes sur ma base de donn&#233;e, j'obtiens des erreurs d'encodag Récupérer des chaines de caractères [ par gaspard83 ] Bonjour &#224; tous, Je voulais savoir si il existait un script php qui permet de r&#233;cup&#233;rer les chaines de caract&#232;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


Nos sponsors


Sondage...

Comparez les prix

CalendriCode

Mai 2012
LMMJVSD
 123456
78910111213
14151617181920
21222324252627
28293031   

Consulter la suite du CalendriCode

A découvrir



 
Développement réalisé par Nicolas SOREL (Nix) avec l'aide de : Cyril DURAND et Emmanuel (EBArtSoft), Merci à Vincent pour ses précieux conseils.
CodeS-SourceS.com© Toute reproduction même partielle est interdite sauf accord écrit du Webmaster
CodeS-SourceS.com© est une marque déposée tous droits réservés

Google Coop CodeS-SourceS Google Coop CodeS-SourceS
Temps d'éxécution de la page : 0,593 sec (3)

Nous contacter | Annoncer sur CodeS-SourceS | Mentions légales