The preg_replace_callback_array()
function returns a string or array of strings, where a set of regular expression matches are replaced by the return value of the callback function.
Note: For each string, the function evaluates the pattern in the given order. The result of evaluating the first pattern on the string will be used as the input string for the second pattern, and so on. This can lead to unexpected behavior.
Show how many letters or numbers each word in a sentence contains:
<?php function countLetters ( $matches ) { return $matches [ 0 ] . '[' . strlen ( $matches [ 0 ] ) . 'letter]' ; } function countDigits ( $matches ) { return $matches [ 0 ] . '[' . strlen ( $matches [ 0 ] ) . 'digit]' ; } $input = "There are 365 days in a year." ; $patterns = [ '/\b[az]+\b/i' => 'countLetters' , '/\b[0-9]+\b/' => 'countDigits' ] ; $result = preg_replace_callback_array ( $patterns , $input ) ; echo $result ; ?>
Try it yourself
This example illustrates the potential unexpected effects that the pattern may have in sequential evaluation. First, the countLetters replacement will add "[4letter]" after "days". After executing the replacement, the countDigits replacement will find "4" in "4letter" and add "[1digit]":
<?php function countLetters ( $matches ) { return $matches [ 0 ] . '[' . strlen ( $matches [ 0 ] ) . 'letter]' ; } function countDigits ( $matches ) { return $matches [ 0 ] . '[' . strlen ( $matches [ 0 ] ) . 'digit]' ; } $input = "365 days" ; $patterns = [ '/[az]+/i' => 'countLetters' , '/[0-9]+/' => 'countDigits' ] ; $result = preg_replace_callback_array ( $patterns , $input ) ; echo $result ; ?>
Try it yourself