Tot*_*oro 31 php unicode utf-8
是否可以输入一个字符并获得unicode值?例如,我可以将⽇放在html中输出"⽇",是否可以将该字符作为参数提供给函数并将数字作为输出而不构建unicode表?
$val = someFunction("?");//returns 12103
Run Code Online (Sandbox Code Playgroud)
还是反过来?
$val2 = someOtherFunction(12103);//returns "?"
Run Code Online (Sandbox Code Playgroud)
我希望能够将实际字符输出到页面而不是代码,如果可能的话,我也希望能够从字符中获取代码.我得到的最接近我想要的是php.net/manual/en/function.mb-decode-numericentity.php,但是我不能让它工作,这是我需要的代码还是我在错误的轨道上?
Mar*_*ker 34
function _uniord($c) {
if (ord($c{0}) >=0 && ord($c{0}) <= 127)
return ord($c{0});
if (ord($c{0}) >= 192 && ord($c{0}) <= 223)
return (ord($c{0})-192)*64 + (ord($c{1})-128);
if (ord($c{0}) >= 224 && ord($c{0}) <= 239)
return (ord($c{0})-224)*4096 + (ord($c{1})-128)*64 + (ord($c{2})-128);
if (ord($c{0}) >= 240 && ord($c{0}) <= 247)
return (ord($c{0})-240)*262144 + (ord($c{1})-128)*4096 + (ord($c{2})-128)*64 + (ord($c{3})-128);
if (ord($c{0}) >= 248 && ord($c{0}) <= 251)
return (ord($c{0})-248)*16777216 + (ord($c{1})-128)*262144 + (ord($c{2})-128)*4096 + (ord($c{3})-128)*64 + (ord($c{4})-128);
if (ord($c{0}) >= 252 && ord($c{0}) <= 253)
return (ord($c{0})-252)*1073741824 + (ord($c{1})-128)*16777216 + (ord($c{2})-128)*262144 + (ord($c{3})-128)*4096 + (ord($c{4})-128)*64 + (ord($c{5})-128);
if (ord($c{0}) >= 254 && ord($c{0}) <= 255) // error
return FALSE;
return 0;
} // function _uniord()
Run Code Online (Sandbox Code Playgroud)
和
function _unichr($o) {
if (function_exists('mb_convert_encoding')) {
return mb_convert_encoding('&#'.intval($o).';', 'UTF-8', 'HTML-ENTITIES');
} else {
return chr(intval($o));
}
} // function _unichr()
Run Code Online (Sandbox Code Playgroud)
bob*_*nce 24
这是基于以下内容的unichr/uniord的更紧凑的实现pack:
// code point to UTF-8 string
function unichr($i) {
return iconv('UCS-4LE', 'UTF-8', pack('V', $i));
}
// UTF-8 string to code point
function uniord($s) {
return unpack('V', iconv('UTF-8', 'UCS-4LE', $s))[1];
}
Run Code Online (Sandbox Code Playgroud)
MAC*_*rha 10
如果您使用的是PHP7.2(或更高版本),则无需定义新函数。Multibyte String扩展有两个功能供您使用!
要获取字符的代码点(即Unicode值),请使用mb_ord();并要从该值中获取特定字符,请使用mb_chr()。
例如:
mb_chr(12103, "utf8"); // ?
mb_ord("?", "utf8"); // 12103
Run Code Online (Sandbox Code Playgroud)
这也有效,(对于理解位移的人来说,这可能比Mark Bakers的回答更具可读性):
public function ordinal($str){
$charString = mb_substr($str, 0, 1, 'utf-8');
$size = strlen($charString);
$ordinal = ord($charString[0]) & (0xFF >> $size);
//Merge other characters into the value
for($i = 1; $i < $size; $i++){
$ordinal = $ordinal << 6 | (ord($charString[$i]) & 127);
}
return $ordinal;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
25509 次 |
| 最近记录: |