Sindup:isUtf8
De Hegyd Doc.
Version du 31 janvier 2012 à 15:54 par Vanina Lebouvier (discuter | contributions)
En C
for (i = 0; (c = utf[i]); i+= nb, nb = 0) {
if( (c & 0x80) != 0x80) // 1 octet
nb = 1;
else if ((c & 0xE0) == 0xC0) // 2 octets
nb = 2;
else if ((c & 0xF0) == 0xE0) // 3 octets
nb = 3;
else if ((c & 0xF8) == 0xF0) // 4 octets
nb = 4;
else if ((c & 0xFC) == 0xF8) // 5 octets
nb = 5;
else if ((c & 0xFE) == 0xFC) // 6 octets
nb = 6;
else
return 1; // N'est pas de l'utf8
for( j = 1; j < nb && (c = utf[i+j]); j++) {
if( (c & 0xC0) != 0x80)
return 1;
}
}
En php
// Détecte si la le text est bien constitué uniquement d'utf8
public function isUtf8( $str) {
for( $i = 0; $i < strlen( $str); $i+= $nb, $nb = 0) {
$c = ord( $str[$i]);
if( ( $c & 0x80) != 0x80)
$nb = 1; # 0xxx xxxx
elseif( ( $c & 0xE0) == 0xC0)
$nb = 2; # 110x xxxx
elseif( ( $c & 0xF0) == 0xE0)
$nb = 3; # 1110 xxxx
elseif( ( $c & 0xF8) == 0xF0)
$nb = 4; # 1111 0xxx
elseif( ( $c & 0xFC) == 0xF8)
$nb = 5; # 1111 10xx
elseif( ( $c & 0xFE) == 0xFC)
$nb = 6; # 1111 110x
else
return false; # Does not match any model
for( $j = 1; $j < $nb && ($i + $j) < strlen( $str); $j++) {
if( ( ord( $str[$i]) & 0xC0) != 0x80)
return false;
}
}
return true;
}
Caractères UTF8 sur :
- 1 octet :
0xxx xxxx c1 & 0x80 != 0x80
- 2 octets :
110x xxxx - 10xx xxxx c1 & 0xE0 == 0xC0 c2 & 0xC0 == 0x80
- 3 octets :
1110 xxxx - 10xx xxxx - 10xx xxxx c1 & 0xF0 == 0xE0 c2 & 0xC0 == 0x80 c3 & 0xC0 == 0x80
- 4 octets :
1111 0xxx - 10xx xxxx - 10xx xxxx - 10xx xxxx c1 & 0xF8 == 0xF0 ... c4 & 0xC0 == 0x80
- 5 octets :
1111 10xx - 10xx xxxx - 10xx xxxx - 10xx xxxx - 10xx xxxx c1 & 0xFC == 0xF8 ... c5 & 0xC0 == 0x80
- 6 octets :
1111 110x - 10xx xxxx - 10xx xxxx - 10xx xxxx - 10xx xxxx - 10xx xxxx c1 & 0xFE == 0xFC ... c6 & 0xC0 == 0x80
