Current Location: Home> Function Categories> preg_replace_callback_array

preg_replace_callback_array

Perform a regular expression search and use callback replacement
Name:preg_replace_callback_array
Category:Regular processing PCRE
Programming Language:php
One-line Description:Given an array that associates an expression with a callback function, returns a string where all matches of each expression are replaced with the substring returned by the callback function.

Definition and usage

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.

Example

Example 1

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

Example 2

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