Home  >  Article  >  Backend Development  >  How to use php to convert unicode to ordinary strings (code example)

How to use php to convert unicode to ordinary strings (code example)

不言
不言forward
2019-01-31 10:24:204062browse

本篇文章给大家带来的内容是关于如何使用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 .= &#39;0&#39;;//补位高字节 0

    return &#39;\\u&#39; . $_sup . $unicode; //加上 \u  返回
  }

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

    $_ret_unicode = &#39;&#39;;
    foreach ($_arr_str as $_str) $_ret_unicode .= get_unicode($_str);

    return $_ret_unicode;
  }

测试效果:

$_str_test = &#39;see,你看我哪里像好人&#39;;
  $_unicode = unicode_encode($_str_test);
  echo $_str_test . &#39; <b style="color: red">=></b> &#39; . $_unicode, &#39;<br><br>&#39;;
  echo $_unicode . &#39; <b style="color: red">=></b> &#39; . unicode_decode($_unicode), &#39;<br><br>&#39;;
  echo $_unicode . &#39; <b style="color: red">=></b> &#39; . unicode_decode_by_json($_unicode), &#39;<br><br>&#39;;

The above is the detailed content of How to use php to convert unicode to ordinary strings (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete