search
HomeBackend DevelopmentPHP TutorialPHP实现Unicode和Utf-8互相转换

  一. 编码原理及实现

  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
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
PHP's Purpose: Building Dynamic WebsitesPHP's Purpose: Building Dynamic WebsitesApr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP: Handling Databases and Server-Side LogicPHP: Handling Databases and Server-Side LogicApr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

How do you prevent SQL Injection in PHP? (Prepared statements, PDO)How do you prevent SQL Injection in PHP? (Prepared statements, PDO)Apr 15, 2025 am 12:15 AM

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

PHP and Python: Code Examples and ComparisonPHP and Python: Code Examples and ComparisonApr 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 in Action: Real-World Examples and ApplicationsPHP in Action: Real-World Examples and ApplicationsApr 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: Creating Interactive Web Content with EasePHP: Creating Interactive Web Content with EaseApr 14, 2025 am 12:15 AM

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python: Comparing Two Popular Programming LanguagesPHP and Python: Comparing Two Popular Programming LanguagesApr 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.

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.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools