php unicode转字符串

<?php
/**
 * @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  $_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 strtoupper($_ret_unicode);
}

echo unicode_encode("你好今天咋样");
echo PHP_EOL;

  去掉u  特殊设备使用

原文地址:https://www.cnblogs.com/pxjbk/p/11813620.html