PHP automatic character set judgment and transcoding
Source: Internet
Author: User
This article provides a detailed analysis of PHP's automatic judgment of character sets and transcoding. For more information, see the principle. because gb2312/gbk is a two-byte Chinese character, these two bytes have a value range, while the Chinese character in UTF-8 is three bytes, and each byte also has a value range. The English language only occupies one byte (excluding the full width), regardless of the encoding ).
For file encoding checks, you can also directly check the BOM information of UTF-8. Let's not say much about it. the function is used to check and transcode strings.
The code is as follows:
Function safeEncoding ($ string, $ outEncoding = 'utf-8 ')
{
$ Encoding = "UTF-8 ";
For ($ I = 0; $ I {
If (ord ($ string {$ I}) <128)
Continue;
If (ord ($ string {$ I}) & 224) = 224)
{
// The first byte is determined
$ Char = $ string {++ $ I };
If (ord ($ char) & 128) = 128)
{
// The second byte is passed
$ Char = $ string {++ $ I };
If (ord ($ char) & 128) = 128)
{
$ Encoding = "UTF-8 ";
Break;
}
}
}
If (ord ($ string {$ I}) & 192) = 192)
{
// The first byte is determined
$ Char = $ string {++ $ I };
If (ord ($ char) & 128) = 128)
{
// The second byte is passed
$ Encoding = "GB2312 ";
Break;
}
}
}
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.