php中 ord() 和 chr() 处理 utf8 字符串

时间:2021-06-14 12:49:56

ord()  : 将字符转为 ascii 码 (0-256),准确定义官方文档:http://php.net/manual/en/function.ord.php

chr() : 将 ascii 码转为字符,与 ord() 相反

不过这两个方法都有限制,只能处理 ascii 码,

如果需要处理的字符串包含 utf-8 ,就不能正常工作,假如 你使用的 php 是大于 7.2.0 版本,那么你可以使用增强的方法:

mb_ord()

mb_chr()

如果使用的 php 版本小于 7.2.0,可以尝试使用以下方法:

ord_utf8()

  function ord_utf8($string, &$offset) {
$code = ord(substr($string, $offset,1));
if ($code >= 128) { //otherwise 0xxxxxxx
if ($code < 224) $bytes_number = 2; //110xxxxx
else if ($code < 240) $bytes_number = 3; //1110xxxx
else if ($code < 248) $bytes_number = 4; //11110xxx
$code_temp = $code - 192 - ($bytes_number > 2 ? 32 : 0) - ($bytes_number > 3 ? 16 : 0);
for ($i = 2; $i <= $bytes_number; $i++) {
$offset ++;
$code2 = ord(substr($string, $offset, 1)) - 128; //10xxxxxx
$code_temp = $code_temp*64 + $code2;
}
$code = $code_temp;
}
$offset += 1;
if ($offset >= strlen($string)) $offset = -1;
return $code;
}

用法:

<?php
$text = "abcàê߀abc"; $offset = 0; //$offset is a reference, as it is not easy to split a utf-8 char-by-char. Useful to iterate on a string: while ($offset >= 0) {
echo $offset.": ".ordutf8($text, $offset)."\n";
} //-----------------------------------------
/* returns:
0: 97
1: 98
2: 99
3: 224
5: 234
7: 223
9: 8364
12: 97
13: 98
14: 99
*/
?>

chr_utf8()

     function chr_utf8 ($codes) {
if (is_scalar($codes)) $codes= func_get_args();
$str= '';
foreach ($codes as $code) $str.= html_entity_decode('&#'.$code.';',ENT_NOQUOTES,'UTF-8');
return $str;
}

用法和 chr() 一样;

参考:http://php.net/manual/en/function.ord.php
           http://php.net/manual/en/function.chr.php

ps: 这两个方法都是本人查看官方文档时,翻阅页面底部的 用户贡献 所看到的,建议平时查看官方文档时多留意底部的 用户贡献
 php中 ord() 和 chr() 处理 utf8 字符串