Quick Tip:

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);

Leave a Reply

Your email address will not be published.