Quick Tip: “e” Modifier For Regular Expression

regex Quick Tip: e Modifier For Regular Expression

There’s a question about regular expression on WPQuestions yesterday that received some interesting solutions. The question is replace all semicolons between [[ and ]]. I myself found a solution uses “e” modifier which I think interesting.

My solution is:

$s = "In [[ find_date_for_quote(); find_date_for_quote(); ]] IBM was  struggling to avoid bankruptcy.";

$s = preg_replace('#[[.*?]]#e', "str_replace(';', '', '$0')", $s);

echo $s;

The interesting thing here is str_replace function is used inside preg_replace, and that helps remove all semicolons. We can do that because of “e” modifier (at the end of pattern). It allows us to use any PHP code in the replacement.

Here is another example modified from PHP Manual which will turn all HTML tags in a string into lowercase:

preg_replace("/(</?)(w+)([^>]*>)/e", "'\1'.strtolower('\2').'\3'", $html_body);
Posted in: PHP

Leave a Reply