将字符串转换为其对应的实体

Convert string to it's correspondent entity

所以我有这个匿名函数,可以将我的字符串的每个字符转换为实体。

var myStr = myStr.replace(/[\u0022\u0027\u0080-\FFFF]/g, function(a) {
   return '&#' + a.charCodeAt(0) + ';';
});  

我需要对 PHP 做同样的事情。
我将有一个普通字符串 将其转换为等效的实体代码 .
例如:

有 --> 想要:Képzeld el PDF ------>Képzeld el PDF

我在读 preg_replace_callback

Perform a regular expression search and replace using a callback

但我不知道如何在 PHP 中应用同样的东西。
我也可以在 preg_replace 中使用匿名函数,像这样:

 $line = preg_replace_callback(
        '/[\u0022\u0027\u0080-\FFFF]/g',
        function ($matches) {
            return '&#' + a.charCodeAt(0) + ';';
        },
    );

我无法让它工作或找到 charCodeAt 的等价物。 preg_replace 函数甚至不支持正则表达式范围的字符。

您可以使用 IntlChar::ord() 来查找字符的代码点。以下是转译版本:

$myStr = preg_replace_callback('~[\x{0022}\x{0027}\x{0080}-\x{ffff}]~u', function ($c) {
    return '&#' . IntlChar::ord($c[0]) . ';';
}, $myStr);

live demo