PHP code used to determine whether the string encoding is UTF-8

Source: Internet
Author: User

We used the mb_detect_encoding () function to detect character encoding.

 

The code is as follows: Copy code
// Determine the encoding of a string
If ($ tag = mb_convert_encoding ($ tag, "GB2312", "UTF-8"), "UTF-8", "GB2312 ")){
}
Else {// if it is gb2312, it will be converted to utf8
$ Tag = mb_convert_encoding ($ tag, 'utf-8', 'gb2312 ');
}

$ Keytitle = "% D0 % BE % C6 % AC. The detection results are UTF-8. This bug is not actually a bug, when writing the program should not be too dependent on mb_detect_encoding, when the string is short, the possibility of deviation of the detection results is very large.
How can this problem be solved? My solution is:

The code is as follows: Copy code

$ Encode = mb_detect_encoding ($ keytitle, array ('ascii ', 'gb2312 & prime;, 'gbk', 'utf-8 ');

Parameters are: the input variables to be detected, the encoding method detection sequence (once true, it is automatically ignored later), and the strict mode.
Adjust the encoding detection sequence to minimize the possibility of conversion errors.

The above solution still cannot be solved, and another solution is found below.

Example 1

The code is as follows: Copy code

// Returns true if $ string is valid UTF-8 and false otherwise.
Function is_utf8 ($ word)
{
If (preg_match ("/^ ([". chr (1, 228 ). "-". chr (1, 233 ). "] {1 }[". chr (1, 128 ). "-". chr (1, 191 ). "] {1 }[". chr (1, 128 ). "-". chr (1, 191 ). "] {1}) {1}/", $ word) = true | preg_match ("/([". chr (1, 228 ). "-". chr (1, 233 ). "] {1 }[". chr (1, 128 ). "-". chr (1, 191 ). "] {1 }[". chr (1, 128 ). "-". chr (1, 191 ). "] {1}) {1} $/", $ word) = true | preg_match ("/([". chr (1, 228 ). "-". chr (1, 233 ). "] {1 }[". chr (1, 128 ). "-". chr (1, 191 ). "] {1 }[". chr (1, 128 ). "-". chr (1, 191 ). "] {1}) {2,}/", $ word) = true)
{
Return true;
}
Else
{
Return false;
}
} // Function is_utf8

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.