php - 将 unicode 转换为 html 实体十六进制

标签 php unicode hex html-entities

如何将 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 然后使用 unpackvsprintf 来满足格式化需求。

如果你更喜欢 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/

相关文章:

php - 如何将关联数组映射到 html 元素属性?

php - 当我发送外键时,Laravel Eloquent 无法插入行?

php - 使用 php 或 avconv 获取 .mov 视频旋转

python - Python 中的 Unicode 全角到标准 ASCII(反之亦然)

java - 从字符串到十六进制 MD5 哈希并返回

php - 将 mySQL 数据库信息放入 JavaScript 数组

python - pyPdf 忽略 PDF 文件中的换行符

delphi - 使用 Delphi 2007 解码 UTF-8 编码的西里尔字母

c++ - 将十六进制字节发送到串行端口

c# - 从字符串计算 Modbus RTU 的 CRC