php输出字符unicode码,[PHP]单字符Unicode编码解码函数
PHP 自帶函數(shù)里面似乎是沒(méi)有能夠?qū)ψ址蜃址M(jìn)行直接轉(zhuǎn)換的函數(shù),百度了一下,發(fā)現(xiàn)了一個(gè)封裝函數(shù)能用。
精簡(jiǎn)過(guò)后的函數(shù)內(nèi)部還是會(huì)經(jīng)過(guò)幾次編碼轉(zhuǎn)換,但是我發(fā)現(xiàn)編碼之后對(duì)特殊字符的轉(zhuǎn)換有問(wèn)題,索性再精簡(jiǎn)直接去掉了編碼。
所以函數(shù)現(xiàn)在只支持UTF-8且只能單字符(傳入字符串返回錯(cuò)值)
function char_unicode($str, $DECODE = True) {
$result = '';
if ($DECODE === False) {
$unicodestr = intval(base_convert(bin2hex(iconv('utf-8', 'UCS-4', $str)), 16, 10));
$result = $unicodestr;
} else {
$temp = intval($str);
$result = iconv('UCS-2BE', 'utf-8', ($temp < 256) ? chr(0) . chr($temp) : chr($temp / 256) . chr($temp % 256));
}
return $result;
}
需要的是單字符編碼,對(duì)此函數(shù)進(jìn)行了一點(diǎn)精簡(jiǎn)和修改,精簡(jiǎn)后默認(rèn)UTF-8是沒(méi)有問(wèn)題的,本人對(duì)編碼的認(rèn)知不深,所以對(duì)其他編碼能否完美支持這里不做測(cè)試了。
測(cè)試效果:
函數(shù)內(nèi)容:
/**
* $str 編碼字符串
* $DECODE 是否解碼
* $encoding 字符串的編碼,默認(rèn)utf-8
*/
function char_unicode($str, $DECODE = True, $encoding = 'utf-8') {
$result = '';
if ($DECODE !== True) {
$str = iconv($encoding, "gb2312", $str);
if (ord(substr($str, 0, 1)) < 0xA1) { //如果為英文則取1個(gè)字節(jié)
$row = iconv("gb2312", $encoding, substr($str, 0, 1));
} else {
$row = iconv("gb2312", $encoding, substr($str, 0, 2));
}
//轉(zhuǎn)換Unicode碼
$unicodestr = base_convert(bin2hex(iconv($encoding, 'UCS-4', $row)), 16, 10);
$result = $unicodestr;
} else {
$temp = intval($str);
$unistr = ($temp < 256) ? chr(0) . chr($temp) : chr($temp / 256) . chr($temp % 256);
$result = iconv('UCS-2', $encoding, $unistr);
}
return $result;
}
測(cè)試代碼:
header('Content-type:application/json;;charset=UTF-8');
/**
* $str 編碼字符串
* $DECODE 是否解碼
* $encoding 字符串的編碼,默認(rèn)utf-8
*/
function char_unicode($str, $DECODE = True, $encoding = 'utf-8') {
$result = '';
if ($DECODE !== True) {
$str = iconv($encoding, "gb2312", $str);
if (ord(substr($str, 0, 1)) < 0xA1) { //如果為英文則取1個(gè)字節(jié)
$row = iconv("gb2312", $encoding, substr($str, 0, 1));
} else {
$row = iconv("gb2312", $encoding, substr($str, 0, 2));
}
//轉(zhuǎn)換Unicode碼
$unicodestr = base_convert(bin2hex(iconv($encoding, 'UCS-4', $row)), 16, 10);
$result = $unicodestr;
} else {
$temp = intval($str);
$unistr = ($temp < 256) ? chr(0) . chr($temp) : chr($temp / 256) . chr($temp % 256);
$result = iconv('UCS-2BE', $encoding, $unistr);
}
return $result;
}
$str = "愛(ài)";
$int = char_unicode($str,False);
$unstr = char_unicode($int);
$str2 = char_unicode($unstr,False);
echo 'unicode編碼前:'.$str .PHP_EOL;
echo 'unicode編碼后:'.$unstr.PHP_EOL;
echo 'unicode解碼后:'.$str2.PHP_EOL;
您可以選擇一種方式贊助本站支付寶贊助
微信贊助
分享到各大網(wǎng)站
分享到:更多
總結(jié)
以上是生活随笔為你收集整理的php输出字符unicode码,[PHP]单字符Unicode编码解码函数的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: java console press a
- 下一篇: php 时钟函数,使用PHP的日期与时间