设为首页 加入收藏

TOP

PHP unicode与普通字符串的相互转化
2019-08-23 00:41:39 】 浏览:31
Tags:PHP unicode 普通 字符串 相互 转化

unicode转字符串

方法一:json

  /**
   * unicode转字符串,通过json转化
   * @param $str
   * @return string
   */
  function unicode_decode_by_json($str)
  {
    $json = '{"str":"' . $str . '"}';
    $arr = json_decode($json, true);
    if (empty($arr)) return '';
    return $arr['str'];
  }

 

方法二:

  /**
   * unicode转中文
   * @param $data
   * @return null|string|string[]
   */
  function unicode_decode($data)
  {
    $rs = preg_replace_callback('/\\\\u([0-9a-f]{4})/i', 'replace_unicode_escape_sequence', $data);
    return $rs;
  }

  function replace_unicode_escape_sequence($match)
  {
    return mb_convert_encoding(pack('H*', $match[1]), 'UTF-8', 'UCS-2BE');
  }

 

 

字符串转unicode

 

  /**
   * @param  string $str 需转换字符,这里为单个字符
   * @return string
   */
  function get_unicode($str)
  {
    $bin_str = '';
    $arr = is_array($str) ? $str : str_split($str);//获取字符内部数组表示,此时$arr应类似array(228, 189, 160)
    foreach ($arr as $value) $bin_str .= decbin(ord($value));//转成数字再转成二进制字符串,$bin_str应类似111001001011110110100000,如果是汉字"你"
    $bin_str = preg_replace('/^.{4}(.{4}).{2}(.{6}).{2}(.{6})$/', '$1$2$3', $bin_str);//正则截取, $bin_str应类似0100111101100000,如果是汉字"你"

    $unicode = dechex(bindec($bin_str));//返回unicode十六进制

    $_sup = '';
    for ($i = 0; $i < 4 - strlen($unicode); $i++) $_sup .= '0';//补位高字节 0

    return '\\u' . $_sup . $unicode; //加上 \u  返回
  }

  /**
   * 转化字符串为unicode
   * @param $str string 可单个/复数个
   * @return string
   */
  function unicode_encode($str)
  {
    $_arr_str = preg_split('/(?<!^)(?!$)/u', $str);//拆分字符串为数组(含中文字符)

    $_ret_unicode = '';
    foreach ($_arr_str as $_str) $_ret_unicode .= get_unicode($_str);

    return $_ret_unicode;
  }

 

测试效果:

  $_str_test = 'see,你看我哪里像好人';
  $_unicode = unicode_encode($_str_test);


  echo $_str_test . ' <b style="color: red">=></b> ' . $_unicode, '<br><br>';
  echo $_unicode . ' <b style="color: red">=></b> ' . unicode_decode($_unicode), '<br><br>';
  echo $_unicode . ' <b style="color: red">=></b> ' . unicode_decode_by_json($_unicode), '<br><br>';
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇腾讯地图和百度地图的PHP相互转换 下一篇PHP安装BCMath扩展

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目