php 检测是否为utf-8还是gb2312编码

在php中检测字符串编码的方法有很多,最常用的就是直接使用mb_detect_encoding函数了,但还有更高级的办法就是使用字符的ascii值来判断.

例1代码如下:

  1. function is_utf8($str)
  2. {
  3. $c=0; $b=0;
  4. $bits=0;
  5. $len=strlen($str);
  6. for($i=0; $i<$len; $i++){
  7. $c=ord($str[$i]);
  8. if($c > 128){
  9. if(($c >= 254)) return false;
  10. elseif($c >= 252) $bits=6;
  11. elseif($c >= 248) $bits=5;
  12. elseif($c >= 240) $bits=4;
  13. elseif($c >= 224) $bits=3;
  14. elseif($c >= 192) $bits=2;
  15. else return false;
  16. if(($i+$bits) > $len) return false;
  17. while($bits > 1){
  18. $i++;
  19. $b=ord($str[$i]);
  20. if($b < 128 || $b > 191) return false;
  21. $bits--;
  22. }
  23. }
  24. }
  25. return true;
  26. }

1、方法1,代码如下:

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

2、方法2,代码如下:

  1. function preg_is_utf8($string)
  2. {
  3. return preg_match('/^.*$/u', $string) > 0;//preg_match('/^./u', $string)
  4. }