您现在的位置: 365建站网 > 365文章 > PHP检测字符串是否为UTF8编码函数分享

PHP检测字符串是否为UTF8编码函数分享

文章来源:365jz.com     点击数:210    更新时间:2017-08-23 15:01   参与评论

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

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

例子1

</>code

  1. /**
  2. * 检测字符串是否为UTF8编码
  3. * @param string $str 被检测的字符串
  4. * @return boolean
  5. */
  6. function is_utf8($str){
  7. $len = strlen($str);
  8. for($i = 0; $i < $len; $i++){
  9. $c = ord($str[$i]);
  10. if ($c > 128) {
  11. if (($c > 247)) return false;
  12. elseif ($c > 239) $bytes = 4;
  13. elseif ($c > 223) $bytes = 3;
  14. elseif ($c > 191) $bytes = 2;
  15. else return false;
  16. if (($i + $bytes) > $len) return false;
  17. while ($bytes > 1) {
  18. $i++;
  19. $b = ord($str[$i]);
  20. if ($b < 128 || $b > 191) return false;
  21. $bytes--;
  22. }
  23. }
  24. }
  25. return true;
  26. }
  27. 例子2

</>code

  1. function is_utf8($string) {
  2.      return preg_match('%^(?:
  3.              [\x09\x0A\x0D\x20-\x7E]                 # ASCII
  4.          | [\xC2-\xDF][\x80-\xBF]                 # non-overlong 2-byte
  5.          |     \xE0[\xA0-\xBF][\x80-\xBF]             # excluding overlongs
  6.          | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}     # straight 3-byte
  7.          |     \xED[\x80-\x9F][\x80-\xBF]             # excluding surrogates
  8.          |     \xF0[\x90-\xBF][\x80-\xBF]{2}     # planes 1-3
  9.          | [\xF1-\xF3][\x80-\xBF]{3}             # planes 4-15
  10.          |     \xF4[\x80-\x8F][\x80-\xBF]{2}     # plane 16
  11.      )*$%xs', $string);     
  12. }
  13. 准确率基本和mb_detect_encoding()一样,要对一起对,要错一起错。
  14. 编码检测不可能100%准确,这个东西已经可以基本满足要求了。
  15. 例子3

</>code

  1. function mb_is_utf8($string)  
  2. {  
  3.     return mb_detect_encoding($string, 'UTF-8') === 'UTF-8';//新发现  
  4. }

 

例子4

</>code

  1. // Returns true if $string is valid UTF-8 and false otherwise.  
  2. function is_utf8($word)  
  3. {  
  4. 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)  
  5. {  
  6. return true;  
  7. }  
  8. else  
  9. {  
  10. return false;  
  11. }  
  12. } // function is_utf8

 

希望本文所述对大家的PHP程序设计有所帮助。

如对本文有疑问,请提交到交流论坛,广大热心网友会为你解答!! 点击进入论坛

发表评论 (210人查看0条评论)
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
昵称:
最新评论
------分隔线----------------------------

快速入口

· 365软件
· 杰创官网
· 建站工具
· 网站大全

其它栏目

· 建站教程
· 365学习

业务咨询

· 技术支持
· 服务时间:9:00-18:00
365建站网二维码

Powered by 365建站网 RSS地图 HTML地图

copyright © 2013-2024 版权所有 鄂ICP备17013400号