Where an interpreted language can be useful – Apply a function to backward references with preg_replace

Eveything goes with PHP sauce
We all know the preg_replace function. I have been using it for years and never noticed its behaviour when it is associated with the “e” modifier.

Just take a look at this piece of code:

echo preg_replace(
  '/{(.*?)}/e',
  'strtoupper("$1")',
  '{did you know} you {could} apply {a} function to {a replacement} using preg_replace?'
);

The output is “DID YOU KNOW you COULD apply A function to A REPLACEMENT using preg_replace?”.
We chose strtoupper in the example but any expression would fit.

Note, and this is important, that the function is included in the replacement string.

The trick here is the use of the “e” modifier. The behaviour of preg_replace is then modified to not use the replacement string given to preg_replace but the result of its treatment by eval().

So, beware, the second parameter still must be a valid string and you will need to properly escape it.

  1. No comments yet.

  1. No trackbacks yet.