php输出字符unicode码,[PHP]单字符Unicode编码解码函数
PHP 自帶函數里面似乎是沒有能夠對字符或字符串進行直接轉換的函數,百度了一下,發現了一個封裝函數能用。
精簡過后的函數內部還是會經過幾次編碼轉換,但是我發現編碼之后對特殊字符的轉換有問題,索性再精簡直接去掉了編碼。
所以函數現在只支持UTF-8且只能單字符(傳入字符串返回錯值)
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;
}
需要的是單字符編碼,對此函數進行了一點精簡和修改,精簡后默認UTF-8是沒有問題的,本人對編碼的認知不深,所以對其他編碼能否完美支持這里不做測試了。
測試效果:
函數內容:
/**
* $str 編碼字符串
* $DECODE 是否解碼
* $encoding 字符串的編碼,默認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個字節
$row = iconv("gb2312", $encoding, substr($str, 0, 1));
} else {
$row = iconv("gb2312", $encoding, substr($str, 0, 2));
}
//轉換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;
}
測試代碼:
header('Content-type:application/json;;charset=UTF-8');
/**
* $str 編碼字符串
* $DECODE 是否解碼
* $encoding 字符串的編碼,默認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個字節
$row = iconv("gb2312", $encoding, substr($str, 0, 1));
} else {
$row = iconv("gb2312", $encoding, substr($str, 0, 2));
}
//轉換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 = "愛";
$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;
您可以選擇一種方式贊助本站支付寶贊助
微信贊助
分享到各大網站
分享到:更多
總結
以上是生活随笔為你收集整理的php输出字符unicode码,[PHP]单字符Unicode编码解码函数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java console press a
- 下一篇: php 时钟函数,使用PHP的日期与时间