_php tutorial on Unicode encoding and decoding in PHP

Source: Internet
Author: User
This article is a detailed analysis of the Unicode encoding and decoding in PHP, the need for a friend reference

Method One:

Copy CodeThe code is as follows:
function Unicode_encode ($name)
{
$name = Iconv (' UTF-8 ', ' UCS-2 ', $name);
$len = strlen ($name);
$str = ";
for ($i = 0; $i < $len-1; $i = $i + 2)
{
$c = $name [$i];
$c 2 = $name [$i + 1];
if (ord ($c) > 0)
{//two bytes of text
$str. = ' u '. Base_convert (Ord ($c), ten, 0). Str_pad (Base_convert (Ord ($c 2), ten, 2),, str_pad_left);
}
Else
{
$str. = $c 2;
}
}
return $str;
}
Decoding Unicode-encoded content
function Unicode_decode ($name)
{
Convert encoding to convert Unicode encoding into a utf-8 encoding that can be browsed
$pattern = '/([w]+) | (U ([w]{4}))/I ';
Preg_match_all ($pattern, $name, $matches);
if (!empty ($matches))
{
$name = ";
for ($j = 0; $j < count ($matches [0]); $j + +)
{
$str = $matches [0][$j];
if (Strpos ($str, ' u ') = = = 0)
{
$code = Base_convert (substr ($STR, 2, 2), 16, 10);
$code 2 = Base_convert (substr ($STR, 4), 16, 10);
$c = Chr ($code). Chr ($code 2);
$c = Iconv (' UCS-2 ', ' UTF-8 ', $c);
$name. = $c;
}
Else
{
$name. = $str;
}
}
}
return $name;
}


Method Two:

Copy CodeThe code is as follows:


function Unicode2utf8 ($STR) {
if (! $str) return $str;
$decode = Json_decode ($STR);
if ($decode) return $decode;
$str = ' ["'. $str. '"]';
$decode = Json_decode ($STR);
if (count ($decode) = = 1) {
return $decode [0];
}
return $str;
}

http://www.bkjia.com/PHPjc/372321.html www.bkjia.com true http://www.bkjia.com/PHPjc/372321.html techarticle This article is a detailed analysis of the Unicode encoding and decoding in PHP, the need for a friend reference method one: Copy the code as follows:? PHP function Unicode_encode ($name) ...

  • 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.