如何检查字符串的字符集是否为UTF8?
答案 0 :(得分:33)
不要重新发明轮子。该任务有一个内置函数:mb_check_encoding()
。
mb_check_encoding($string, 'UTF-8');
答案 1 :(得分:15)
只是旁注:
您无法确定给定字符串是否以UTF-8编码。您只能确定给定字符串是否在UTF-8中明确不编码。请参阅相关问题here:
您无法检测给定的字符串 (或字节序列)是UTF-8编码的 文本,例如每一个 UTF-8系列八位字节也是有效的 (如果荒谬的)拉丁文-1系列(或 一些其他编码)八位字节。然而 并非每一系列有效的Latin-1 八位字节是有效的UTF-8系列。
答案 2 :(得分:7)
function is_utf8($string) {
return preg_match('%^(?:
[\x09\x0A\x0D\x20-\x7E] # ASCII
| [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
| \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
| [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
| \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
| \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
| [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
| \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
)*$%xs', $string);
}
我已经查过了。此功能有效。
答案 3 :(得分:6)
更好的是,使用上述两种解决方案。
function isUtf8($string) {
if (function_exists("mb_check_encoding") && is_callable("mb_check_encoding")) {
return mb_check_encoding($string, 'UTF8');
}
return preg_match('%^(?:
[\x09\x0A\x0D\x20-\x7E] # ASCII
| [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
| \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
| [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
| \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
| \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
| [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
| \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
)*$%xs', $string);
}
答案 4 :(得分:1)
mb_detect_encoding($string);
将返回$string
的实际字符集。如果mb_check_encoding($string, 'UTF-8');
的字符集为UTF-8,则$string
将返回 TRUE FALSE
答案 5 :(得分:0)
如果它从服务器
发送给你echo $_SERVER['HTTP_ACCEPT_CHARSET'];
答案 6 :(得分:0)
以上答案都不正确。是的,他们可能正在工作。如果您使用preg_replace
功能获得答案,如果您处理了很多混乱,您是否试图杀死您的服务器?使用这个没有正则表达式的纯PHP函数,100%的时间工作,而且速度更快。
if(function_exists('grk_Is_UTF8') === FALSE){
function grk_Is_UTF8($String=''){
# On va calculer la longeur de la chaîne
$Len = strlen($String);
# On va boucler sur chaque caractère
for($i = 0; $i < $Len; $i++){
# On va aller chercher la valeur ASCII du caractère
$Ord = ord($String[$i]);
if($Ord > 128){
if($Ord > 247){
return FALSE;
} elseif($Ord > 239){
$Bytes = 4;
} elseif($Ord > 223){
$Bytes = 3;
} elseif($Ord > 191){
$Bytes = 2;
} else {
return FALSE;
}
#
if(($i + $Bytes) > $Len){
return FALSE;
}
# On va boucler sur chaque bytes / caractères
while($Bytes > 1){
# +1
$i++;
# On va aller chercher la valeur ASCII du caractère / byte
$Ord = ord($String[$i]);
if($Ord < 128 OR $Ord > 191){
return FALSE;
}
# Parfait
$Bytes--;
}
}
}
# Vrai
return TRUE;
}
}