1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
| <?php
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;
|