Home Backend Development PHP Tutorial PHP实现Unicode和Utf-8互相转换

PHP实现Unicode和Utf-8互相转换

Jun 23, 2016 pm 01:25 PM

  一. 编码原理及实现

  unicode编码是实现utf-8与gb系列编码(gb2312、gbk、gb18030)转换的基础,虽然我们也可以直接做一个utf-8到这些编码 的对照表,但很少有人会这么做,因为utf-8的可变编码具有不确定性,因此一般情况使用都是unicode与gb编码的对照 表,unicode(UCS-2)实际上是utf-8的基础编码,utf-8只是它的一种实现而已,两者存在下面的对应关系:

Unicode符号范围           | UTF-8编码方式

u0000 0000 - u0000 007F   | 0xxxxxxx

u0000 0080 - u0000 07FF   | 110xxxxx 10xxxxxx

u0000 0800 - u0000 FFFF   | 1110xxxx 10xxxxxx 10xxxxxx

  由于目前utf-8使用的字符都是居于UCS-2的,因此对于4-6字节编码的情况是不必考虑的,同样地,在反向转换的时候,如果出现四字节以上的 utf-8字符,可以直接视为乱码忽略掉或转为unicode实体形式("long int;"形式),然后交给浏览器或相关解析程序去处理,用php把unicode转为utf-8编码的算法如下:

/*

  * 参数 $c 是unicode字符编码的int类型数值,如果是用二进制读取的数据,在php中通常要用 hexdec(bin2hex( $bin_unichar )) 这样转换

  */

function uni2utf8( $c )

{

   if ( $c

   {

         $utf8char = chr ( $c );

   }

   else if ( $c

   {

         $utf8char = chr (0xC0 | $c >> 0x06). chr (0x80 | $c & 0x3F);

   }

   else if ( $c

   {

         $utf8char = chr (0xE0 | $c >> 0x0C). chr (0x80 | $c >> 0x06 & 0x3F). chr (0x80 | $c & 0x3F);

   }

   //因为UCS-2只有两字节,所以后面的情况是不可能出现的,这里只是说明unicode HTML实体编码的用法。

   else

   {

         $utf8char = "{$c};" ;

   }

   return $utf8char ;

}


在目前的环境范围内,可以认为 utf-8字符集==unicode(UCS-2),但从理论上,主要字符集之关的包含关系如下:

utf-8 > unicode(UCS-2) > gb18030 > gbk > gb2312

因此,如果编码都正确的情况下:

gb2312 => gbk => gb18030 => unicode(UCS-2) => utf-8

这样的一个转变过程,基本上是无损的,但反而言之,由

utf-8 => unicode(UCS-2) => gb18030=> gbk => gb2312

这样的转变过程,是很可能存在不能识别的字符的,因此,如果对于使用utf-8编码的系统,尽量不要轻易的去做反向转换编码的操作。


二. 用PHP将Unicode 转化为UTF-8另外一种方法:


function unescape( $str ) {

     $str = rawurldecode( $str );

     preg_match_all( "/(?:%u.{4})|.{4};|\d+;|.+/U" , $str , $r );

     $ar = $r [0];

     //print_r($ar);

     foreach ( $ar as $k => $v ) {

         if ( substr ( $v ,0,2) == "%u" ){

             $ar [ $k ] = iconv( "UCS-2BE" , "UTF-8" ,pack( "H4" , substr ( $v ,-4)));

   }

         elseif ( substr ( $v ,0,3) == "" ){

             $ar [ $k ] = iconv( "UCS-2BE" , "UTF-8" ,pack( "H4" , substr ( $v ,3,-1)));

   }

         elseif ( substr ( $v ,0,2) == "" ) {

             $ar [ $k ] = iconv( "UCS-2BE" , "UTF-8" ,pack( "n" , substr ( $v ,2,-1)));

         }

     }

     return join( "" , $ar );

}


Linux 服务器上 UCS-2 编码方式与 Winodws 不一致,以下是有关两个平台 UCS-2 编码的潜规则:

1. UCS-2 不等于 UTF-16。 UTF-16 每个字节使用 ASCII 字符范围编码,而 UCS-2 对每个字节的编码可以超出 ASCII 字符范围。UCS-2 和 UTF-16 对每个字符至多占两个字节,但是他们的编码是不一样的。

2. 对于 UCS-2, windows 下默认是 UCS-2LE。用 MultibyteToWidechar(或者A2W)生成的是 UCS-2LE 的 unicode。windows记事本可以将文本保存为 UCS-2BE,相当于多了层转换。

3. 对于 UCS-2, linux 下默认是 UCS-2BE。用iconv(指定UCS-2)来转换生成的是 UCS-2BE 的 unicode。如果转换windows平台过来的 UCS-2, 需要指定 UCS-2LE。

4. 鉴于windows和linux等多个平台对 UCS-2 的理解不同(UCS-2LE,UCS-2BE)。MS 主张 unicode 有个引导标志(UCS-2LE FFFE, UCS-2BE FEFF),以表明下面的字符是 unicode 并且判别 big-endian 或 little-endian。 所以从 windows 平台过来的数据发现有这个前缀,不用慌张。

5. linux 的编码输出,比如从文件输出,从 printf 输出,需要控制台做适当的编码匹配(如果编码不匹配,一般和该程序编译时的编码有若干关系),而控制台的转换输入需要查看当前的系统编码。比如控制台当前 的编码是 UTF-8, 那么 UTF-8 编码的东西能正确显示,GBK 就不能;同样,当前编码是 GBK, 就能显示 GBK 编码,后来的系统应该更智能的处理好更多的转换了。不过通过 putty 等终端还是需要设置好终端的编码转换以解除乱码的烦恼。

三.再提供一对PHP中对汉字进行UNICODE完整的编码和解码的实现供参考:

//将内容进行UNICODE编码

function unicode_encode( $name )

{

     $name = iconv( 'UTF-8' , 'UCS-2' , $name );

     $len = strlen ( $name );

     $str = '' ;

     for ( $i = 0; $i

     {

         $c = $name [ $i ];

         $c2 = $name [ $i + 1];

         if (ord( $c ) > 0)

         {  

             // 两个字节的文字

             $str .= '\u' . base_convert (ord( $c ), 10, 16). base_convert (ord( $c2 ), 10, 16);

         }

         else

         {

             $str .= $c2 ;

         }

     }

     return $str ;

}

// 将UNICODE编码后的内容进行解码

function unicode_decode( $name )

{

     // 转换编码,将Unicode编码转换成可以浏览的utf-8编码

     $pattern = '/([\w]+)|(\\\u([\w]{4}))/i' ;

     preg_match_all( $pattern , $name , $matches );

     if (! empty ( $matches ))

     {

         $name = '' ;

         for ( $j = 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 ;

}


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1665
14
PHP Tutorial
1269
29
C# Tutorial
1249
24
PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

How does PHP type hinting work, including scalar types, return types, union types, and nullable types? How does PHP type hinting work, including scalar types, return types, union types, and nullable types? Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

See all articles