php自动识别文字编码并转换
时间:2021-07-01 10:21:17
帮助过:17人阅读
- /**
- * @ string 需要转换的文字
- * @ encoding 目标编码
- **/
- function detect_encoding($string,$encoding = 'gbk'){
- $is_utf8 = preg_match('%^(?:[\x09\x0a\x0d\x20-\x7e]| [\xc2-\xdf][\x80-\xbf]| \xe0[\xa0-\xbf][\x80-\xbf] | [\xe1-\xec\xee\xef][\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');
- }
- }
|