所以我有这个匿名函数将字符串的每个字符转换为实体。
var myStr = myStr.replace(/[\u0022\u0027\u0080-\FFFF]/g, function(a) {
return '&#' + a.charCodeAt(0) + ';';
});
我需要对PHP做同样的事情 我将有一个普通的字符串,将它转换为等效的实体代码 例如:
有 - >想要:Képzeld el PDF
-------> Képzeld el PDF
执行正则表达式搜索并使用回调替换
但我不知道如何在PHP中应用同样的东西 我也可以在preg_replace中使用annonymous函数,如下所示:
$line = preg_replace_callback(
'/[\u0022\u0027\u0080-\FFFF]/g',
function ($matches) {
return '&#' + a.charCodeAt(0) + ';';
},
);
我无法使其发挥作用或找到charCodeAt
的等效性。
preg_replace
函数不支持正则表达式的字符范围。
答案 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