PHP:将 UTF8 字符编码为 html 个实体

PHP: Encode UTF8-Characters to html entities

我想将普通字符编码为 html-实体,例如

a => a
A => A
b => b
B => B

但是

echo htmlentities("a");

不起作用。它在 html 源代码中输出正常字符 (a A b B) 而不是 html 实体。

如何转换它们?

您可以使用 mb_ord or IntlChar::ord 相当轻松地为此构建一个函数,其中任何一个都会为您提供 Unicode 代码点的数值。

然后您可以使用 base_convert 将其转换为十六进制字符串,并添加“&#x”和“;”围绕它给出一个 HTML 实体:

function make_entity(string $char) {
    $codePoint = mb_ord($char, 'UTF-8'); // or IntlChar::ord($char); 
    $hex = base_convert($codePoint, 10, 16);
    return '&#x' . $hex . ';';
}
echo make_entity('a');
echo make_entity('€');
echo make_entity('');

然后您需要 运行 为您的 UTF-8 字符串中的每个代码点。 不足以使用substr之类的东西遍历字符串,因为PHP的字符串函数使用单独的字节,每个UTF-8代码点可能是多个字节。

一种方法是使用具有 /./u:

模式的正则表达式替换
  • . 匹配每个“字符”
  • /u 修饰符开启 Unicode 模式,因此 . 匹配的每个“字符”都是一个完整的代码点

然后您可以 运行 上面的 make_entity 函数用于每个匹配项(即每个代码点) preg_replace_callback


因为 preg_replace_callback 会向你的回调传递一个匹配数组,而不仅仅是一个字符串,你可以创建一个 arrow function 接受数组并将元素 0 传递给真正的函数:

$callback = fn($matches) => make_entity($matches[0]);

所以把它放在一起,你有这个:

echo preg_replace_callback('/./u', fn($m) => make_entity($m[0]), 'a€');

箭头函数是在 PHP 7.4 中引入的,所以如果你坚持使用旧版本,你可以编写与常规相同的东西 anonymous function:

echo preg_replace_callback('/./u', function($m) { return make_entity($m[0]) }, 'a€');

或者当然,只是一个常规的命名函数(或 class 或对象上的方法;有关不同的语法选项,请参阅 the "callable" page in the manual):

function make_entity_from_array_item(array $matches) {
    return make_entity($matches[0]);
}
echo preg_replace_callback('/./u', 'make_entity_from_array_item', 'a€');