这篇文章主要介绍了php检测字符串是否为utf8编码的常用方法,列举了四个实例从不同的角度来实现这一功能,是非常实用的技巧,具有一定的学习借鉴价值,需要的朋友可
本文实例总结了php检测字符串是否为utf8编码的常用方法。分享给大家供大家参考。具体实现方法如下:
检测字符串编码可以有很多种方法,如利用ord获得字符的进制然后进入判断,或利用mb_detect_encoding函数来处理,下面整理了四种常用方法供大家参考。
例子1
复制代码 代码如下:
/**
* 检测字符串是否为utf8编码
* @param string $str 被检测的字符串
* @return boolean
*/
function is_utf8($str){
$len = strlen($str);
for($i = 0; $i $c = ord($str[$i]);
if ($c > 128) {
if (($c > 247)) return false;
elseif ($c > 239) $bytes = 4;
elseif ($c > 223) $bytes = 3;
elseif ($c > 191) $bytes = 2;
else return false;
if (($i + $bytes) > $len) return false;
while ($bytes > 1) {
$i++;
$b = ord($str[$i]);
if ($b 191) return false;
$bytes--;
}
}
}
return true;
}
例子2
复制代码 代码如下:
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);
}
准确率基本和mb_detect_encoding()一样,,要对一起对,要错一起错。
编码检测不可能100%准确,这个东西已经可以基本满足要求了。
例子3
复制代码 代码如下:
function mb_is_utf8($string)
{
return mb_detect_encoding($string, 'utf-8') === 'utf-8';//新发现
}
例子4
复制代码 代码如下:
// returns true if $string is valid utf-8 and false otherwise.
function is_utf8($word)
{
if (preg_match(/^([.chr(228).-.chr(233).]{1}[.chr(128).-.chr(191).]{1}[.chr(128).-.chr(191).]{1}){1}/,$word) == true || preg_match(/([.chr(228).-.chr(233).]{1}[.chr(128).-.chr(191).]{1}[.chr(128).-.chr(191).]{1}){1}$/,$word) == true || preg_match(/([.chr(228).-.chr(233).]{1}[.chr(128).-.chr(191).]{1}[.chr(128).-.chr(191).]{1}){2,}/,$word) == true)
{
return true;
}
else
{
return false;
}
} // function is_utf8
希望本文所述对大家的php程序设计有所帮助。