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

PHP Basic Tutorial

PHP Advanced Tutorial

PHP & MySQL

PHP Reference Manual

PHP preg_replace_callback_array() Function Usage and Example

PHP Regular Expression (PCRE)

The preg_replace_callback_array() function performs a regular expression search and uses a callback for replacement.

This function is supported in PHP7+ Version Support.

Syntax

mixed preg_replace_callback_array ( array $patterns_and_callbacks , mixed $subject [, int $limit =) -1 [, int &$count ]] )

Function Similar to preg_replace_callback(), but it is based on each pattern match to call the callback function for replacement.

Parameter Description:

  • $patterns_and_callbacks: Associative array, key(pattern) => value(callback function)

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

  • $limit: Optional, the maximum number of replacements for each pattern, default is -1(Unlimited, replace all matches).

  • $count: Optional, specify the number of replacements.

Return Value

If subject is an array, return an array; otherwise, return a string. Return NULL if an error occurs.

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

Online Example

<?php
$subject = 'Aaaaaa Bbb';
preg_replace_callback_array(
    [
        '~[a]+~i' => function ($match) {
            echo strlen($match[0]), ' matches for "a" found', PHP_EOL;
        },
        '~[b]+~i' => function ($match) {
            echo strlen($match[0]), ' matches for "b" found', PHP_EOL;
        }
    ],
    $subject
);
?>

The execution result is as follows:

6 matches for "a" found
3 matches for "b" found

PHP Regular Expression (PCRE)