zoukankan      html  css  js  c++  java
  • 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>';
  • 相关阅读:
    Scala学习笔记--集合类型Queue,Set
    Hadoop学习笔记-HDFS命令
    Spark添加/更改集群节点需要修改的配置文件
    Spark学习笔记-如何运行wordcount(使用jar包)
    Scala学习文档-列表的使用
    Python yaml 使用的包
    Python 通过命令行安装包的时候 pip 提示错误
    Python 注释
    Python 关键字
    Python 数据类型
  • 原文地址:https://www.cnblogs.com/coder404/p/10030899.html
Copyright © 2011-2022 走看看