PHP检测字符串是否为UTF8编码的常用方法
本实例汇总了PHP中用于验证字符串是否采用UTF-8编码的主流技术手段,旨在为开发者提供实用的参考方案。以下是具体的代码实现细节。
针对字符串编码的检测存在多种技术路径,例如通过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通过组合多个正则条件来验证UTF-8有效性: 复制代码 代码如下:// 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编程工作带来实际帮助。