preg_replace_callback
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.
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