Php automatically identifies the text encoding and converts it to the target encoding method,

Source: Internet
Author: User

Php automatically identifies the text encoding and converts it to the target encoding method,

This example describes how php automatically identifies the text encoding and converts it to the target encoding. Share it with you for your reference. The details are as follows:

When PHP processes the page, we use iconv or mb_convert functions for character set conversion. However, this is actually a prerequisite. That is, we must know in and out encoding in advance before we can perform the correct conversion.

Although most conversions are performed between gbk and UTF-8, what should I do if I do not know the encoding of the conversion object? Google's safeEncoding function can easily identify UTF-8 and GBK encoding. This function is very accurate to some extent, but it is not so useful in some complex environments. below I combined the differences between GBK and UTF-8 encoding, using regular expressions to determine the UTF-8 encoding and using the mb_convert_encoding function for conversion. in China, basically more popular encoding is GBK and UTF-8, so this function is for the two encoding for automatic conversion.

/*** @ String the text to be converted * @ encoding destination 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 ');}}

I hope this article will help you with php programming.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.