Encoding conversion between GB2312 and Unicode (UTF-8) using PHP

Source: Internet
Author: User

The following example converts gb2312 to a uft-8 form
The iconv function after php4.3.1 is very useful, but you only need to write a conversion function from uft8 to unicode.
Check the table (gb2312.txt).

<?
$ Text = "e-book library ";
Preg_match_all ("/[x80-xff]?. /", $ Text, $ ar );
Foreach ($ ar [0] as $ v)
Echo "& #". utf8_unicode (iconv ("GB2312", "UTF-8", $ v )).";";
?>
<?
// Utf8-> unicode
Function utf8_unicode ($ c ){
Switch (strlen ($ c )){
Case 1:
Return ord ($ c );
Case 2:
$ N = (ord ($ c [0]) & 0x3f) <6;
$ N = ord ($ c [1]) & 0x3f;
Return $ n;
Case 3:
$ N = (ord ($ c [0]) & 0x1f) <12;
$ N = (ord ($ c [1]) & 0x3f) <6;
$ N = ord ($ c [2]) & 0x3f;
Return $ n;
Case 4:
$ N = (ord ($ c [0]) & 0x0f) <18;
$ N = (ord ($ c [1]) & 0x3f) <12;
$ N = (ord ($ c [2]) & 0x3f) <6;
$ N = ord ($ c [3]) & 0x3f;
Return $ n;
}
}
?>

The following example is to use php to convert the encoding in the uft-8 to gb2312.

<? Php
$ Str = "TTL auto-focus around the clock ";
$ Str = preg_replace ("| & # ([0-9] {1, 5}); |", "". u2utf82gb (1). "", $ str );
$ Str = "$ str =" $ str ";";
Eval ($ str );
Echo $ str;
Function u2utf82gb ($ c ){
$ Str = "";
If ($ c <0x80 ){
$ Str. = $ c;
} Else if ($ c <0x800 ){
$ Str. = chr (0xC0 | $ c> 6 );
$ Str. = chr (0x80 | $ c & 0x3F );
} Else if ($ c <0x10000 ){
$ Str. = chr (0xE0 | $ c> 12 );
$ Str. = chr (0x80 | $ c> 6 & 0x3F );
$ Str. = chr (0x80 | $ c & 0x3F );
} Else if ($ c <0x200000 ){
$ Str. = chr (0xF0 | $ c> 18 );
$ Str. = chr (0x80 | $ c> 12 & 0x3F );
$ Str. = chr (0x80 | $ c> 6 & 0x3F );
$ Str. = chr (0x80 | $ c & 0x3F );
}
Return iconv ('utf-8', 'gb2312 ', $ str );
}
?>

Use javascript for conversion

<Style>
BODY {

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.