Menu Riverview Church

PREG_REPLACE_CALLBACK

Perform a regular expression search and replace using a callback

SYNTAX

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

PARAMETERS

pattern

The pattern to search for. It can be either a string or an array with strings.

callback

A callback that will be called and passed an array of matched elements in the subject string. The callback should return the replacement string. This is the callback signature:

handler ( array $matches ) : string
subject

The string or an array with strings to search and replace.

limit

The maximum possible replacements for each pattern in each subject string. Defaults to -1 (no limit).

count

If specified, this variable will be filled with the number of replacements done.

flags

flags can be a combination of the PREG_OFFSET_CAPTURE and PREG_UNMATCHED_AS_NULL flags, which influence the format of the matches array.

PREG_OFFSET_CAPTURE For every occurring match the appendant string offset (in bytes) will also be returned. Note that this changes the value of matches into an array where every element is an array consisting of the matched string at offset 0 and its string offset into subject at offset 1.
PREG_UNMATCHED_AS_NULL Unmatched subpatterns are reported as NULL; otherwise they are reported as an empty string.

RETURN

preg_replace_callback() returns an array if the subject parameter is an array, or a string otherwise. On errors the return value is NULL.

If matches are found, the new subject will be returned, otherwise subject will be returned unchanged.

EXAMPLES

PATTERN CALLBACK SUBJECT

New Years Day: 2020-01-01
Christmas Eve: 2020-12-24
Christmas Day: 2020-12-25
New Years Eve: 2020-12-31

LIMIT

New Years Day: 2020-01-01
Christmas Eve: 2020-12-24
Christmas Day: 12/25/2001
New Years Eve: 12/31/2001

COUNT

New Years Day: 2020-01-01
Christmas Eve: 2020-12-24
Christmas Day: 2020-12-25
New Years Eve: 2020-12-31
4

FLAGS | PREG_OFFSET_CAPTURE

New Years Day: 2020-01-01 (21 15 18)
Christmas Eve: 2020-12-24 (47 41 44)
Christmas Day: 2020-12-25 (73 67 70)
New Years Eve: 2020-12-31 (99 93 96)

FLAGS | PREG_UNMATCHED_AS_NULL

NULL NULL '2001'
'12' '24' '2001'
'12' '25' '2001'
NULL NULL '2001'
New Years Day: 2020
Christmas Eve: 2020-12-24
Christmas Day: 2020-12-25
New Years Eve: 2020

PHP