Analysis of UNICODE encoding and decoding in PHP _ PHP Tutorial-php Tutorial

Source: Internet
Author: User
Analysis of UNICODE encoding and decoding in PHP. Method 1: Copy the code as follows :? Phpfunctionunicode_encode ($ name) {$ nameiconv (UTF-8, UCS-2, $ name); $ lenstrlen ($ name); $ str; for ($ i0; $ I $ len-1; $ I Method 1:

The 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];
$ C2 = $ name [$ I + 1];
If (ord ($ c)> 0)
{// Two-byte text
$ Str. = '\ U '. base_convert (ord ($ c), 10, 16 ). str_pad (base_convert (ord ($ c2), 10, 16), 2, 0, STR_PAD_LEFT );
}
Else
{
$ Str. = $ c2;
}
}
Return $ str;
}
// Decodes the UNICODE encoded content
Function unicode_decode ($ name)
{
// Convert the Unicode encoding to the UTF-8 encoding that can be viewed
$ 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 );
$ Code2 = base_convert (substr ($ str, 4), 16, 10 );
$ C = chr ($ code). chr ($ code2 );
$ C = iconv ('ucs-2', 'utf-8', $ c );
$ Name. = $ c;
}
Else
{
$ Name. = $ str;
}
}
}
Return $ name;
}


Method 2:

The 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;
}

The pipeline code is as follows :? Php function unicode_encode ($ name) {$ name = iconv ('utf-8', 'ucos-2', $ name); $ len = strlen ($ name ); $ str = ''; for ($ I = 0; $ I $ len-1; $ I =...

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.