The preg_replace_callback() function in PHP (
Page 1 of 5 )
The preg_replace_callback() function is an under-utilized and little documented PHP function that you will find useful and powerful in many situations, especially if you have been actively using preg_match() and preg_replace(). In this article, you will find a clear explanation of what this function does, together with carefully crafted examples that illustrate some of its uses.preg_replace() vs. preg_replace_callback()
The best way to understand the preg_replace_callback() function is to compare it with the preg_replace() function.
The example below is a script written using the preg_replace() function. It simply converts a date in MMDDYY format into YYMMDD.
<?php
$string = '12/25/08';
$pattern = '|(d{2})/(d{2})/(d{2})|';
$replacement = '$3$1$2';
echo preg_replace($pattern, $replacement, $string);
?>
The output of the script above is:

The example below shows a second script that accomplishes the same thing, but using the preg_replace_callback() function.
<?php
$string = '12/25/08';
$pattern = '|(d{2})/(d{2})/(d{2})|';
$callback_fn = 'process';
echo preg_replace_callback($pattern, $callback_fn, $string);
function process($matches) {
print_r($matches);
return $matches[3].$matches[1].$matches[2];
}
?>
And here’s the output:

Comparing the two scripts, you will notice that the two functions – preg_replace () and preg_replace_callback() – are almost exactly the same. The only difference is that instead of specifying a replacement string for the second parameter, we specify a callback function.
The callback function is called every time there is a match with the regular expression you have specified in the first parameter of preg_replace_callback().
When a callback function gets called, it will be passed an array of matched elements in the first argument. In the example above, it’s the variable $matches. Note that this is the same array you would get from a preg_match() function, i.e. $matches[0] will contain the text that matched the full pattern, $matches[1] will have the text that matched the first captured parenthesized subpattern, and so on.
In the example script above, I included a print_r($matches) so that you can take a look at the array of matched elements that has been passed to the callback function.
At the end of the callback function, we return a string. This is the replacement string for the matched item. Note that if you want to leave the matched string untouched, return a $matches[0] (i.e. the original string). If you want to remove the matched string, return an empty string.