Regex Guru

Friday, 21 March 2008

preg_replace_callback

Filed under: Regex Code — Jan Goyvaerts @ 10:48

I just added a paragraph about preg_replace_callback to the PHP reference on regular-expressions.info. This function is just like preg_replace, with one important difference: instead of passing the replacement as a literal string (or array of strings), you pass it the name of a function. This function will be called for each match. In the function, you can do whatever calculations you want to produce the replacement text.

Guess what the following code does:

$result = preg_replace_callback('/(\d+)\+(\d+)/', compute_replacement, $subject);

function compute_replacement($groups) {
  // You can vary the replacement text for each match on-the-fly
  // $groups[0] holds the regex match
  // $groups[n] holds the match for capturing group n
  return $groups[1] + $groups[2];
}

A few other programming languages have similar functionality. E.g. in .NET, you’d pass a MatchEvaluator instance to the Regex.Replace() method. RegexBuddy can already generate such code snippets for .NET and Java. The PHP version will be added in the next free minor update.

1 Comment

  1. Or use Perl, where you can insert arbitrary code in any location of a regular expression—something that’s very, very flexible.

    Comment by Andri — Tuesday, 1 April 2008 @ 1:22

Sorry, the comment form is closed at this time.