当前位置:首页 > Web开发 > 正文

php中文和unicode互转

2024-03-31 Web开发

unicode转中文时可以使用json_decode()函数实现。

中文转unicode时需要对字符串转换成UCS-4编码,再转成16进制,,再从16进制转换成10进制加上&#前缀来实现中文转unicode编码。

一、unicode转中文

php

<?php

//unicode转中文

function unicodeDecode($unicode_str){

    $json = ‘{"str":"‘.$unicode_str.‘"}‘;

    $arr = json_decode($json,true);

    if(empty($arr)) return ‘‘;

    return $arr[‘str‘];

}

 

$unicode_str = "\u4e2d\u56fd";

echo unicodeDecode($unicode_str);

二、中文转unicode

php

//中文转unicode

function UnicodeEncode($str){

    //split word

    preg_match_all(‘/./u‘,$str,$matches);

 

    $unicodeStr = "";

    foreach($matches[0] as $m){

        //拼接

        $unicodeStr .= "&#".base_convert(bin2hex(iconv(‘UTF-8‘,"UCS-4",$m)),16,10);

    }

    return $unicodeStr;

}

 

$str = "新浪微博";

echo UnicodeEncode($str);

php中文和unicode互转

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/web/40011.html