Home  >  Article  >  Backend Development  >  关于PHP自动判断字符集并转码的详解_php技巧

关于PHP自动判断字符集并转码的详解_php技巧

WBOY
WBOYOriginal
2016-05-17 08:58:30980browse

原理很简单,因为gb2312/gbk是中文两字节,这两个字节是有取值范围的,而utf-8中汉字是三字节,同样每个字节也有取值范围。而英文不 管在何种编码情况下,都是小于128,只占用一个字节(全角除外)。
如果是文件形式的编码检查,还可以直接check utf-8的BOM信息。话不多说,直接上函数,这个函数是用来对字符串进行检查和转码的。

复制代码 代码如下:

function safeEncoding($string,$outEncoding ='UTF-8')   
{   
 $encoding = "UTF-8";   
 for($i=0;$i {   
  if(ord($string{$i})        continue;   

  if((ord($string{$i})&224)==224)   
  {   
     //第一个字节判断通过   
       $char = $string{++$i};   
     if((ord($char)&128)==128)   
       {   
             //第二个字节判断通过   
           $char = $string{++$i};   
             if((ord($char)&128)==128)   
           {   
                $encoding = "UTF-8";   
                break;   
           }   
         }   
   }   

  if((ord($string{$i})&192)==192)   
       {   
           //第一个字节判断通过   
          $char = $string{++$i};   
         if((ord($char)&128)==128)   
           {   
            // 第二个字节判断通过   
                $encoding = "GB2312";   
    break;   
   }   
      }   
 }   

 if(strtoupper($encoding) == strtoupper($outEncoding))   
  return $string;   
 else  
        return iconv($encoding,$outEncoding,$string);   
}
?>

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn