PHP unicode與普通字符串的相互轉化

unicode轉字符串

方法一:jsonjson

  /**
   * 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>';
相關文章
相關標籤/搜索