PHP Learning Note string encoding conversion and judgment _php tips

Source: Internet
Author: User

Copy Code code as follows:

Iconv (' GBK ', ' utf-8//ignore ', ' cloud-dwelling community '); Converts a string from GBK encoding to UTF-8 encoding

However, the iconv can only solve the situation in which the encoding is known, and if the string encoding is unknown, you need to probe its encoding first, and you may use the Mb_string extension library:

Copy Code code as follows:

Mb_detect_encoding (' cloud-dwelling community ');

However, there is a mishap in mb_detect_encoding, often appear to judge inaccurate situation. Perhaps this can be solved:

Copy Code code as follows:

It is inefficient to use iconv conversion and to judge whether it is equivalent.
function Is_utf8 ($STR) {
if ($str = = Iconv (' UTF-8 ', ' Utf-8//ignore ', $str)) {
Return ' UTF-8 ';
}
}
A variety of coding scenarios
function detect_encoding ($STR) {
foreach (Array (' GBK ', ' UTF-8 ') as $v) {
if ($str = = Iconv ($v, $v. '//ignore ', $str)) {
return $v;
}
}
}

After obtaining the string encoding information in the above way, we can use Iconv or mb_convert_encoding to convert the encoding.

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.