So I have this annonymous function that converts every character of my string into entity.
var myStr = myStr.replace(/[\u0022\u0027\u0080-\FFFF]/g, function(a) {
return '&#' + a.charCodeAt(0) + ';';
});
I need to do the same with PHP.
I'll have a normal string and transform it it's equivalent entity code.
e.g:
Have --> Want: Képzeld el PDF
------->Képzeld el PDF
I was reading about preg_replace_callback
Perform a regular expression search and replace using a callback
But I don't know how to apply the same thing in PHP.
I could also use the annonymous function within preg_replace, like so:
$line = preg_replace_callback(
'/[\u0022\u0027\u0080-\FFFF]/g',
function ($matches) {
return '&#' + a.charCodeAt(0) + ';';
},
);
I couldn't make it work or find an equivalence for charCodeAt
. Even the regex range of characters are not supported by preg_replace
function.
You could use IntlChar::ord()
to find the codepoint of a character. Below is a transpiled version:
$myStr = preg_replace_callback('~[\x{0022}\x{0027}\x{0080}-\x{ffff}]~u', function ($c) {
return '&#' . IntlChar::ord($c[0]) . ';';
}, $myStr);
See live demo