Use PHP to determine whether the file is UTF-8 encoding (check Bom) _ PHP Tutorial

Source: Internet
Author: User
Tags 0xc0
Use PHP to determine if the file is UTF-8 encoded (check Bom ). UTF-8 encoding files are divided into two types with Bom and without Bom, with Bom are easy to handle, without Bom will be a bit of trouble, so write a function to judge, the code is as follows: the returned UTF-8 encoding files are divided into two types, with Bom and without Bom, with Bom is easy to handle, without Bom will be a bit of trouble, therefore, I wrote a function to judge the code. the code is as follows:

// Returns 1, indicating that all characters are not greater than 127)
// 2 indicates UTF8
// Return 0, indicating normal gb encoding

Function TestUtf8 ($ text)
{
If (strlen ($ text) <3) return false;
$ Lastch = 0;
$ Begin = 0;
$ BOM = true;
$ BOMchs = array (0xEF, 0xBB, 0xBF );
$ Good = 0;
$ Bad = 0;
$ NotAscii = 0;
For ($ I = 0; $ I <strlen ($ text); $ I ++)
{
$ Ch = ord ($ text [$ I]);
If ($ begin <3)
{
$ BOM = ($ BOMchs [$ begin] = $ ch );
$ Begin + = 1;
Continue;
}

If ($ begin = 4 & $ BOM) break;

If ($ ch> = 0x80) $ notAscii ++;

If ($ ch & 0xC0) = 0x80)
{
If ($ lastch & 0xC0) = 0xC0)
{
$ Good + = 1;
}
Else if ($ lastch & 0x80) = 0)
{
$ Bad + = 1;
}
}
Else if ($ lastch & 0xC0) = 0xC0)
{
$ Bad + = 1;
}
$ Lastch = $ ch;
}
If ($ begin = 4 & $ BOM)
{
Return 2;
}
Else if ($ notAscii = 0)
{
Return 1;
}
Else if ($ good >=$ bad)
{
Return 2;
}
Else
{
Return 0;
}
}

Returns...

Related Article

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.