Home >Backend Development >PHP Tutorial >PHP learning: how to convert unicode and ordinary strings into each other
方法一: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视频教程
The above is the detailed content of PHP learning: how to convert unicode and ordinary strings into each other. For more information, please follow other related articles on the PHP Chinese website!