PHP preg_replace_callback() Function

PHP 正则表达式(PCRE)PHP Regular Expressions (PCRE)

The preg_replace_callback() function performs a regular expression search and uses a callback to do the replacement.

Syntax

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

Except that a callback can be specified in place of replacement to calculate the replacement string, this function is equivalent to preg_replace() in all other aspects.

Parameter description:

  • $pattern: The pattern to search for. It can be a string or an array of strings.

  • $callback: A callback function that is called each time a replacement is needed. The function receives the matched results from subject.

  • $subject: The target string or array of strings to search and replace.

  • $limit: Optional. The maximum possible replacements for each pattern in each subject string. The default is -1 (no limit).

  • $count: Optional. The number of times the replacement is performed.

Return Value

If subject is an array, preg_replace_callback() returns an array; otherwise, it returns a string. On error, it returns NULL.

If a match is found, the replaced target string (or array of strings) is returned. Otherwise, subject is returned unchanged.

Examples

Example 1

<?php //Increase the year in the text by one year. $text = "April fools day is 04/01/2002\n"; $text.= "Last christmas was 12/24/2001\n"; //Callback function function next_year($matches) { //Usually: $matches //$matches //and so on 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 正则表达式(PCRE)PHP Regular Expressions (PCRE)

Other Extensions