About PHP automatic judgment character set and transcoding code of the detailed

Source: Internet
Author: User
Tags character set ord

The principle is very simple, because the GB2312/GBK is Chinese two bytes, these two bytes is a range of values, and utf-8 Chinese characters are three bytes, also have a range of values for each byte. The English language is less than 128, regardless of the encoding, and occupies only one byte (except all corners).
If it is a file-form code check, you can also check Utf-8 's BOM information directly. To say, directly on the function, this function is used to check the string and transcoding.

Copy Code code as follows:


<?php
function safeencoding ($string, $outEncoding = ' UTF-8 ')
{
$encoding = "UTF-8";
for ($i =0; $i <strlen ($string); $i + +)
{
if (Ord ($string {$i}) <128)
Continue

if ((Ord ($string {$i}) &224) ==224)
{
The first byte is judged by
$char = $string {+ + $i};
if ((Ord ($char) &128) ==128)
{
The second byte is judged by
$char = $string {+ + $i};
if ((Ord ($char) &128) ==128)
{
$encoding = "UTF-8";
Break
}
}
}

if ((Ord ($string {$i}) &192) ==192)
{
The first byte is judged by
$char = $string {+ + $i};
if ((Ord ($char) &128) ==128)
{
The second byte is judged by
$encoding = "GB2312";
Break
}
}
}

if (Strtoupper ($encoding) = = Strtoupper ($outEncoding))
return $string;
Else
Return Iconv ($encoding, $outEncoding, $string);
}

?>

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.