PHP检测字符串是否为UTF8编码的常用方法

yipeiwu_com4年前PHP代码库

本文实例总结了PHP检测字符串是否为UTF8编码的常用方法。分享给大家供大家参考。具体实现方法如下:

检测字符串编码可以有很多种方法,如利用ord获得字符的进制然后进入判断,或利用mb_detect_encoding函数来处理,下面整理了四种常用方法供大家参考。

例子1

复制代码 代码如下:
/**
* 检测字符串是否为UTF8编码
* @param string $str 被检测的字符串
* @return boolean
*/
function is_utf8($str){
$len = strlen($str);
for($i = 0; $i < $len; $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 < 128 || $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程序设计有所帮助。

相关文章

php Memcache 中实现消息队列

对于一个很大的消息队列,频繁进行进行大数据库的序列化 和 反序列化,有太耗费。下面是我用PHP 实现的一个消息队列,只需要在尾部插入一个数据,就操作尾部,不用操作整个消息队列进行读取,与...

PHP压缩html网页代码(清除空格,换行符,制表符,注释标记)

PHP压缩html网页代码 (清除空格,换行符,制表符,注释标记)。 有个不错的方法就是压缩HTML,压缩html 其实就是:清除换行符,清除制表符,去掉注释标记 。它所起到的作用不可小...

php函数连续调用实例分析

本文实例讲述了php函数连续调用的方法。分享给大家供大家参考。具体如下: <?php //返回$this,实现连续调用 class xin { function...

php将数据库导出成excel的方法

上传cvs并导入到数据库中,测试成功(部分代码不规范,如PHP_SELF那里要改写成$_SERVER["PHP_SELF"] ) PHP代码 复制代码 代码如下: <?php $f...

PHP单例模式实例分析【防继承,防克隆操作】

本文实例讲述了PHP单例模式。分享给大家供大家参考,具体如下: <?php //单列模式 // //1.普通类 // class singleton{ // } //...