现在的位置: 网页制作教程网站制作经验 >正文
php网上学习

在php中如何对中文进行UNICODE编码以及解码还原

发表于2018/7/13 网站制作经验 0条评论 ⁄ 热度 3,626℃

我们知道UNICODE编码可以解决网页里中文乱码的问题,比如“网站源码”对应的UNICODE编码为“\u7f51\u7ad9\u6e90\u7801”。

那么我们在php中如何对中文进行UNICODE编码以及将UNICODE编码还原解码成汉字中文。

PHP将中文进行UNICODE编码的代码实例。

<?php
//将内容进行UNICODE编码,编码后的内容格式:\u7f51\u7ad9\u6e90\u7801 (原始:网站源码)
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)
    {    // 两个字节的文字
      $str .= '\u'.base_convert(ord($c), 10, 16).base_convert(ord($c2), 10, 16);
    }
    else
    {
      $str .= $c2;
    }
  }
  return $str;
}

PHP将UNICODE编码解码的代码实例。

// 将UNICODE编码后的内容进行解码,编码后的内容格式:\u7f51\u7ad9\u6e90\u7801 (原始:网站源码)
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 < 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;
}

以上是php实现的UNICODE编码和UNICODE解码函数,下面我们测试下,测试代码如下:

//编码
$name = '网站源码';
echo '<h3>'.unicode_encode($name).'</h3>';
//解码
echo '<h3>'.unicode_decode('\u7f51\u7ad9\u6e90\u7801').'</h3>';
  • 暂无评论