您好,欢迎访问一九零五行业门户网

PHP判断字符串编码是否为utf-8的程序代码

我们以前常用mb_detect_encoding()此函数检测字符编码,代码如下:
//判断字符串是什么编码 if ($tag === mb_convert_encoding(mb_convert_encoding($tag, gb2312, utf-8), utf-8, gb2312)) { } else {//如果是gb2312 的就转换为utf8的 $tag = mb_convert_encoding($tag, 'utf-8', 'gb2312'); }
$keytitle = %d0%be%c6%ac;时,检测结果却是utf-8.这个bug其实不算是bug,写程序时也不应当过于依赖mb_detect_encoding,当字符串较短时,检测结果产生偏差的可能性很大,怎么解决呢,我的办法是:
$encode = mb_detect_encoding($keytitle, array('ascii','gb2312','gbk','utf-8');
参数分别是:被检测的输入变量、编码方式的检测顺序(一旦为真,后面自动忽略)、strict模式,对编码检测的顺序进行调整,将最大可能性放在前面,这样减少被错误转换的机会.
上面办法还是解决不了,下面又找到了一个解决方法,代码如下:
function is_utf8($string){ return !strlen( preg_replace( ',[\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 . ',ss', '', $string));}
其它类似信息

推荐信息