php中文汉字与16进制编码转换三种方法

php.cn
Release: 2016-07-25 08:53:51
Original
1767 people have browsed it
  1. //汉字转换为16进制编码
  2. function hexencode($s) {
  3. return preg_replace('/(.)/es',"str_pad(dechex(ord('\\1')),2,'0',str_pad_left)",$s);
  4. }
  5. //16进制编码转换为汉字
  6. function hexdecode($s) {
  7. return preg_replace('/(\w{2})/e',"chr(hexdec('\\1'))",$s);
  8. }
  9. echo hexdecode(hexencode("北京欢迎您!"));
  10. ?>
复制代码

方法2,

  1. echo rawurlencode("北京欢迎您").'
    ';
复制代码

返回字符串,此字符串中除了 -_. 之外的所有非字母数字字符都将被替换成百分号(%)后跟两位十六进制数。 解码用:rawurldecode

方法3, gbk版: gbk编码中一个汉字由二个字符组成, 通过ord()函数获取字符的ascii值如果大于127时,就可以确定当前字符为一个汉字的前半部分,还需要获取汉字的后半部分。 当然,这种判断的方法要结合具体的开发环境,如果存在ascii值大于127的单个字符,这种方法判断显然就不正确。

php实现中文字符转十进制的原理就是通过for循环的方法获取一个汉字的二个字符,然后使用ord()函数把各字符转换为十进制。 如上分别是:不 [178 187] 要 [210 170] 迷 [195 212] 恋 [193 181] 哥 [184 231] php 实现中文字符转十六进制的原理: 首先使用ord()函数取出各个中文字符的十进制,具体可查看[php函数篇掌握ord()与chr()函数应用],然后使用dechex()函数把各个中文字符转化为十六进制。 代码:

  1. $string = "北京欢迎您!";
  2. $length = strlen($string);
  3. echo $string;
  4. $result = array();
  5. //十进制
  6. for($i=0;$iif(ord($string[$i])>127){
  7. $result[] = ord($string[$i]).' '.ord($string[++$i]);
  8. }
  9. }
  10. var_dump($result);
  11. echo '
    ';
  12. //十六进制
  13. $strings = array();
  14. foreach($result as $v){
  15. $dec = explode(" ",$v);
  16. $strings[] = dechex($dec[0])." ".dechex($dec[1]);
  17. }
  18. var_dump($strings);
复制代码

utf-8版:

  1. $string = "北京欢迎您!";
  2. $length = strlen($string);
  3. echo $string;
  4. $result = array();
  5. //十进制
  6. for($i=0;$iif(ord($string[$i])>127){
  7. $result[] = ord($string[$i]).' '.ord($string[++$i]).' '.ord($string[++$i]);
  8. }
  9. }
  10. var_dump($result);
  11. echo '
    ';
  12. //十六进制
  13. $strings = array();
  14. foreach($result as $v){
  15. $dec = explode(" ",$v);
  16. $strings[] = dechex($dec[0])." ".dechex($dec[1])." ".dechex($dec[2]);
  17. }
  18. var_dump($strings);
复制代码


source:php.cn
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 [email protected]
Latest Issues
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!