如何将 Unicode 字符串转换为 HTML 实体? (HEX
不是十进制)
例如,将 Français
转换为 Français
。
最佳答案
对于 related question 中缺少的十六进制编码:
$output = preg_replace_callback('/[\x{80}-\x{10FFFF}]/u', function ($match) {
list($utf8) = $match;
$binary = mb_convert_encoding($utf8, 'UTF-32BE', 'UTF-8');
$entity = vsprintf('&#x%X;', unpack('N', $binary));
return $entity;
}, $input);
这类似于@Baba 的回答,使用 UTF-32BE 然后使用 unpack
和 vsprintf
来满足格式化需求。
如果你更喜欢 iconv
而不是 mb_convert_encoding
,它是相似的:
$output = preg_replace_callback('/[\x{80}-\x{10FFFF}]/u', function ($match) {
list($utf8) = $match;
$binary = iconv('UTF-8', 'UTF-32BE', $utf8);
$entity = vsprintf('&#x%X;', unpack('N', $binary));
return $entity;
}, $input);
我发现这个字符串操作比在 Get hexcode of html entities 中更清晰一些。
关于php - 将 unicode 转换为 html 实体十六进制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13280200/