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

时间:2018-05-23 17:49:41

标签: php regex string encode

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

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

  

执行正则表达式搜索并使用回调替换

但我不知道如何在PHP中应用同样的东西 我也可以在preg_replace中使用annonymous函数,如下所示:

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

我无法使其发挥作用或找到charCodeAt的等效性。 preg_replace函数不支持正则表达式的字符范围。

1 个答案:

答案 0 :(得分:1)

您可以使用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