Posts Tagged ‘RegEx’

preg_replace in PHP with /e flag

Wednesday, September 17th, 2008

The /e flag makes the (quoted) replacement string to be treated as PHP-code, so that one can make more complex regex-replacements in a one-liner.

An example: I want to search for a pattern in a string, and replace any occurences with an array element whose key/index equals the occurence.

Without the /e flag this wouldn’t be as easy, because this does not work;

$pattern = '/\{(.*?)\}/i';
$outputline = preg_replace($pattern, $array[\\1], $inputline); //doesn't make any sense

With the /e flag, however, this works like a charm;

$pattern = '/\{(.*?)\}/ei'; //note the /e flag
$outputline = preg_replace($pattern, '$array[\\1]', $inputline); //works with /e flag

This replaces occurences of $pattern in $inputline with $array[OccurenceOfPatternInInputline] and assigns the result to $outputline.