Dayo
Dayo

Reputation: 12785

alternative to preg_replace with "e" modifier

I have this line ...

preg_replace('/([^\x20-\x7e])/e', '"\\\\\\x" . dechex(ord("${1}"))', $string);

... and it is generating an warning about the use of preg_replace() with the /e modifier.

I am looking for some tips on how to replace this regex with an alternative.

I gather that "preg_replace_callback"can be used as an alternative but need some help with actually implementing it.

I have read the PHP manual but still struggling and my question is one of what the relevant preg_replace_callback alternative to the original is.

Is this valid?

function myCallback($matches) {
    return '"\\\\\\x" . dechex(ord($matches[1]))';
}
preg_replace_callback('/([^\x20-\x7e])/', 'myCallback', $string);

Upvotes: 1

Views: 565

Answers (1)

Amber
Amber

Reputation: 526733

You don't return code, you return the actual value you want to replace with, like so:

function myCallback($matches) {
    return "\\\\\\x" . dechex(ord($matches[1]));
}

Upvotes: 2

Related Questions