在php处理页面时,对于字符集的转换都是采用了iconv或mb_convert等函数。
这有一个前提的。事先得知道in和out是什么样的编码,才能进行正确的转换。
虽然大多数转换都是在gbk和utf-8之间转,但如果不知道转换对象的编码怎么办呢?谷歌出来这么一个函数safeencoding,可以简单的识别utf8和gbk的编码。这个函数在一定程度上识别的很准确,但是在一些比较复杂的环境中就不是那么的好用了。
以下结合了gbk和utf-8编码的不同点,使用正则表达式来判断utf-8编码并使用mb_convert_encoding函数来进行转换。
在国内,基本上比较流行的编码就是gbk和utf-8,此函数是针对这两个编码进行自动转换的.
代码:
 
复制代码 代码示例:
<?php
/**     
* @ string 需要转换的文字     
* @ encoding 目标编码     
**/
    function detect_encoding($string,$encoding = 'gbk'){        
    $is_utf8 =  preg_match('%^(?:[x09x0ax0dx20-x7e]| [xc2-xdf][x80-xbf]|  xe0[xa0-xbf][x80-xbf] | [xe1-xecxeexef][x80-xbf]{2}    |  xed[x80-x9f][x80-xbf] |  xf0[x90-xbf][x80-xbf]{2}  | [xf1-xf3][x80-xbf]{3}  |  xf4[x80-x8f][x80-xbf]{2} )*$%xs', $string);        
    if($is_utf8 && $encoding == 'utf8'){        
        return $string;        
    }elseif($is_utf8){        
        return mb_convert_encoding($string, $encoding, "utf-8");             
    }else{        
        return mb_convert_encoding($string, $encoding, 'gbk,gb2312,big5');          
    }        
}