English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Basic PHP Tutorial

Advanced PHP Tutorial

PHP & MySQL

PHP Reference Manual

Usage and examples of the PHP preg_replace_callback() function

PHP Regular Expression (PCRE)

The preg_replace_callback function performs a regular expression search and uses a callback for replacement.

Syntax

mixed preg_replace_callback ( mixed $pattern , callable $callback , mixed $subject [, int $limit = -1 [, int &$count ]] )

The behavior of this function is similar to preg_replace() in all aspects except that it can specify a callback to perform the calculation of the replacement string.

Parameter Description:

  • $pattern: The pattern to be searched, which can be a string or a string array.

  • $callback: A callback function that is called each time a replacement is needed, and the parameters passed to the function are the matched results from the subject.

  • $subject: The target string or string array to be searched and replaced.

  • $limit: Optional, the maximum number of replacements allowed for each pattern on each subject string. The default is-1(Unlimited).

  • $count: Optional, represents the number of replacement operations performed.

Return value

If subject is an array, preg_replace_callback() returns an array, otherwise it returns a string. Returns NULL in case of an error.

If a match is found, return the replaced target string (or string array), otherwise subject will be returned unchanged.

Online Example

<?php
// Increase the year of the text by one.
$text = "April fools day is 04/01/2002\n";
$text .= "Last christmas was 12/24/2001\n";
// callback function
function next_year($matches)
{
  // Generally: $matches[0] is the complete match
  // $matches[1] is the match of the first capturing group
  // etc.
  return $matches[1].($matches[2]+1);
}
echo preg_replace_callback(
            "|(?\d{2}/\d{2}/)(\d{4})|",
            "next_year",
            $text);
?>

The execution result is as follows:

April fools day is 04/01/2003
Last christmas was 12/24/2002

PHP Regular Expression (PCRE)