PHP function of UTF-8 encoding conversion GB2312 without iconv function

Source: Internet
Author: User
Tags strlen utf 8

If the use of Iconv () function conversion code is relatively simple, but many virtual host does not support this component, I find a half-day on the Internet, only to find a gb2312 to Utf-8 method, but not reverse conversion.

This function is as follows:

/*******************************
GB Rotary UTF-8 encoding
*******************************/
function Gb2utf8 ($GBSTR) {
Global $CODETABLE;
if (Trim ($gbstr) = = "") return $gbstr;
if (empty ($CODETABLE)) {
$filename = DirName (__file__). " /gb2312-utf8.table ";
$fp = fopen ($filename, "R");
while ($l = fgets ($fp, 15))
{$CODETABLE [Hexdec (substr ($l, 0, 6)] = substr ($l, 7, 6);}
Fclose ($FP);
}
$ret = "";
$utf 8 = "";
while ($GBSTR) {
if (Ord (substr ($gbstr, 0, 1)) > 127) {
$thisW = substr ($gbstr, 0, 2);
$gbstr = substr ($gbstr, 2, strlen ($GBSTR));
$utf 8 = "";
@ $utf 8 = U2utf8 (Hexdec ($CODETABLE [Hexdec (Bin2Hex ($thisW))-0x8080]);
if ($utf 8!= "") {
for ($i = 0; $i < strlen ($utf 8); $i = 3)
$ret. = Chr (substr ($utf 8, $i, 3));
}
}
Else
{
$ret. = substr ($gbstr, 0, 1);
$gbstr = substr ($gbstr, 1, strlen ($GBSTR));
}
}
return $ret;
}
Unicode Turn UTF8
function U2utf8 ($c) {
for ($i = 0; $i < count ($c); $i)
$str = "";
if ($c < 0x80) {
$str. = $c;
else if ($c < 0x800) {
$str. = (0xc0 | $c >> 6);
$str. = (0x80 | $c & 0x3F);
else if ($c < 0x10000) {
$str. = (0xe0 | $c >> 12);
$str. = (0x80 | $c >> 6 & 0x3F);
$str. = (0x80 | $c & 0x3F);
else if ($c < 0x200000) {
$str. = (0xF0 | $c >> 18);
$str. = (0x80 | $c >> & 0x3F);
$str. = (0x80 | $c >> 6 & 0x3F);
$str. = (0x80 | $c & 0x3F);
}

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.