Preg_replace_callback
With preg_replace_callback, a user-supplied function is called for each match. This function, called the callback function, is passed the $matches array which contains information about the match. The callback function also determines the replacement string.
On the previous page, we invented a regex to match our placeholder tags: /{[^}]*}/. We use that regex with preg_replace_callback, with one modification. We want the text between the curly braces to become available to our callback function. Therefore, we mark that piece as a group by using parenthesis: /{([^}]*)}/.
To see how preg_replace_callback behaves, we use a function which simply prints its argument:
function print_callback($matches) { print_r($matches); } $template = 'Hello {planet}. My name is {name}.'; echo preg_replace_callback('/{([^}]*)}/', 'print_callback', $template);The regex will match twice. It calls the print_callback function, which prints two arrays:
Array ( [0] => {planet} [1] => planet ) Array ( [0] => {name} [1] => name )Just as with preg_match, the array contains the whole match as its first element, and any groups as subsequent elements. It has the contents of our placeholder as second element. We can use that to replace the placeholder with something useful. In that case, we have to return a string:
$data = array('planet' => 'World', 'name' => 'Wiebe'); $template = 'Hello {planet}. My name is {name}.'; function array_callback($matches) { global $data; $key = $matches[1]; return $data[$key]; } echo preg_replace_callback('/{([^}]*)}/', 'array_callback', $template);