Preg_replace_callback_array() in PHP 7

The preg_replace_callback_array() function in PHP 7 performs pattern matching and replacement using multiple regular expressions with their corresponding callback functions. This function allows you to apply different callbacks for different patterns in a single operation.

Syntax

preg_replace_callback_array(patterns, subject, limit, count, flags)

Parameters

  • patterns − An associative array mapping regular expression patterns to callback functions.
  • subject − The input string or array of strings to perform replacements on.
  • limit − Optional. Maximum number of replacements for each pattern. Default is -1 (unlimited).
  • count − Optional. Variable that will contain the number of replacements performed.
  • flags − Optional. Can be PREG_OFFSET_CAPTURE or PREG_UNMATCHED_AS_NULL.

Return Value

Returns a string or array of strings with replacements made. Returns NULL on error.

Example

Here's how to use preg_replace_callback_array() to count different character groups −

<?php
    $subject = 'AaaaaaaBbbbCccc';
    preg_replace_callback_array(
        [
            '~[a]+~i' => function ($match) {
                echo strlen($match[0]) . ' number of "a" found' . PHP_EOL;
            },
            '~[b]+~i' => function ($match) {
                echo strlen($match[0]) . ' number of "b" found' . PHP_EOL;
            },
            '~[c]+~i' => function ($match) {
                echo strlen($match[0]) . ' number of "c" found' . PHP_EOL;
            }
        ],
        $subject
    );
?>
7 number of "a" found
4 number of "b" found
4 number of "c" found

Practical Example

Here's an example showing actual text replacement using different patterns −

<?php
    $text = "Visit our website at http://example.com or email us at info@example.com";
    
    $result = preg_replace_callback_array(
        [
            '/http:\/\/[^\s]+/' => function($matches) {
                return '<a href="' . $matches[0] . '">' . $matches[0] . '</a>';
            },
            '/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/' => function($matches) {
                return '<a href="mailto:' . $matches[0] . '">' . $matches[0] . '</a>';
            }
        ],
        $text
    );
    
    echo $result;
?>
Visit our website at <a href="http://example.com">http://example.com</a> or email us at <a href="mailto:info@example.com">info@example.com</a>

Conclusion

The preg_replace_callback_array() function provides an efficient way to apply multiple pattern replacements with custom logic. It's particularly useful when you need different processing for different patterns in a single operation.

Updated on: 2026-03-15T09:40:12+05:30

333 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements