Home > Article > Backend Development > PHP's judgment on the current encoding and corresponding encoding conversion implementation skills
This article mainly introduces PHP's judgment on the current encoding and the corresponding encoding conversion implementation skills. Interested friends can refer to it. I hope it will be helpful to everyone.
Below I combine the differences between GBK and UTF-8 encoding, use regular expressions to determine UTF-8 encoding and use the mb_convert_encoding function to convert. In China, basically the more popular encodings are GBK and UTF-8, so this function automatically converts these two encodings.
/** * @ 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'); } }
Summary: The above is the entire content of this article, I hope it will be helpful to everyone's learning.
Related recommendations:
Detailed explanation of the definition and usage of PHP download remote file class
PHP implements the function of generating image thumbnails based on the GD library Method
Detailed explanation of PHP file upload class and usage
The above is the detailed content of PHP's judgment on the current encoding and corresponding encoding conversion implementation skills. For more information, please follow other related articles on the PHP Chinese website!