首页 > 语言 > PHP > 正文

php mb_detect_encoding判断字符串编码方法

2024-09-04 11:48:28
字体:大 中 小
来源:转载
供稿:网友

在php中利用mb_detect_encoding可以判断给我们的字符是那个类型的编码了,从而我们就可以利用inconv进行字符转换了,下面给大家介绍几个例子.

例子,利用mb_detect_encoding()判断字符是否为uft-8编码,代码如下:

  1. $encode = mb_detect_encoding($q, array('GB2312','GBK','UTF-8')); 
  2. echo $encode."<br/>"; 
  3. if($encode=="GB2312") 
  4. { 
  5.     $q = iconv("GBK","UTF-8",$q); 
  6. } 
  7. else if($encode=="GBK") 
  8. { 
  9.     $q = iconv("GBK","UTF-8",$q); 
  10. } 
  11. else if($encode=="EUC-CN") 
  12. { 
  13.     $q = iconv("GBK","UTF-8",$q); 
  14. } 
  15. else//CP936 
  16. { 
  17.     //$q = iconv("GB2312","UTF-8",$q); 
  18. } 

可是 mb_detect_encoding 存在一个硬伤,经常出现判断不准确的情况,或许这样就可以解决,代码如下:

  1. // 使用 iconv 转换并判断是否等值,效率不高 
  2. function is_utf8 ($str) { 
  3.     if ($str === iconv('UTF-8', 'UTF-8//IGNORE', $str)) { 
  4.         return 'UTF-8'; 
  5.     } 
  6. } 
  7. // 多种编码的情况 
  8. function detect_encoding ($str) { 
  9.     foreach (array('GBK', 'UTF-8') as $v) { 
  10.         if ($str === iconv($v, $v . '//IGNORE', $str)) { 
  11.             return $v; 
  12.         } 
  13.     } 
  14. } 

通过以上方式得到字符串编码信息后,就可以利用 iconv 或 mb_convert_encoding 来转换编码了.

问题:可是当 $keytitle  = '%D0%BE%C6%AC'; 时,检测结果却是UTF-8,这其实不算是bug,我们不应当过于依赖mb_detect_encoding,当字符串较短时,检测结果产生偏差的可能性很大.

解决方法,代码如下:

$encode = mb_detect_encoding($keytitle, array('ASCII','GB2312′,'GBK’,'UTF-8');

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表