Regular expression flags

2019-04-15 17:17发布

问题:

Can someone explain what the 'e' flag does, or link me to somewhere that does? I couldn't find anything via google.

Example:

preg_replace("/a(b?)c/e", "search_foo_term('\$1')", $str);

回答1:

e (PREG_REPLACE_EVAL)

If this modifier is set, preg_replace() does normal substitution of backreferences in the replacement string, evaluates it as PHP code, and uses the result for replacing the search string. Single quotes, double quotes, backslashes () and NULL chars will be escaped by backslashes in substituted backreferences. Only preg_replace() uses this modifier; it is ignored by other PCRE functions.

http://www.php.net/manual/en/reference.pcre.pattern.modifiers.php

So given this example:

preg_replace("/a(b?)c/e", "search_foo_term('\$1')", $str);

The replacement for the entire match will be what search_foo_term() returns when passed the match for b? .



回答2:

The e flag is deprecated, mostly for security reasons. Use preg_replace_callback instead.