最近工做上使用到了PHP的字符编码和解码功能,然后发现PHP的原生函数 chr 和函数 ord 的功能有限,不支持中文等多字节字符,我后就根据网上的代码整理了一下(主要是在 php 的官网查到的)。
/**
* 数字编码转换为字符
* @param $code
* @return string
*/
function chr_utf8($code)
{
if ($code < 128) {
$utf = chr($code);
} else if ($code < 2048) {
$utf = chr(192 + (($code - ($code % 64)) / 64));
$utf .= chr(128 + ($code % 64));
} else {
$utf = chr(224 + (($code - ($code % 4096)) / 4096));
$utf .= chr(128 + ((($code % 4096) - ($code % 64)) / 64));
$utf .= chr(128 + ($code % 64));
}
return $utf;
}
/**
* 字符转换为数字编码
* @param $string
* @param $offset
* @return float|int
*/
function ord_utf8($string, &$offset)
{
$code = ord(substr($string, $offset, 1));
if ($code >= 128) {
if ($code < 224) {
//otherwise 0xxxxxxx
$bytesnumber = 2;
} else if ($code < 240) {
//110xxxxx
$bytesnumber = 3;
} else if ($code < 248) {
//1110xxxx
$bytesnumber = 4;
}
//11110xxx
$codetemp = $code - 192 - ($bytesnumber > 2 ? 32 : 0) - ($bytesnumber > 3 ? 16 : 0);
for ($i = 2; $i <= $bytesnumber; $i++) {
$offset++;
//10xxxxxx
$code2 = ord(substr($string, $offset, 1)) - 128;
$codetemp = $codetemp * 64 + $code2;
}
$code = $codetemp;
}
$offset += 1;
if ($offset >= strlen($string)) {
$offset = -1;
}
return $code;
}
对应的 javascript 代码函数封装:
function chr_utf8(code) {
return String.fromCharCode(code);
}
function ord_utf8(str) {
return String.prototype.charCodeAt.call(str,0);
//return String.prototype.charCodeAt.call(str);
}