Current Location: Home> Latest Articles> How to understand the use of PHP's preg_replace_callback_array function through the simplest and most complex examples?

How to understand the use of PHP's preg_replace_callback_array function through the simplest and most complex examples?

M66 2025-06-02

In PHP, string processing is a very important part of daily development. The preg_replace_callback_array function is a powerful and flexible tool for replacing parts of a string that conform to multiple regular expression patterns, and can call different callback functions for each match. This article will compare and explain the usage of preg_replace_callback_array through the simplest example and the most complex example to help you understand its use in depth.

1. What is preg_replace_callback_array ?

The preg_replace_callback_array function was added after PHP 7.0. Its function is to call the corresponding callback functions according to the pattern array of multiple regular expressions to match and replace it.

The function prototype is as follows:

 string preg_replace_callback_array(array $patterns_and_callbacks, string $subject [, int $limit = -1 [, int &$count ]])
  • $patterns_and_callbacks : an array, the key is a regular expression pattern, and the value is the corresponding callback function.

  • $subject : The string to be replaced.

  • $limit : The number of replacements is limited, and the default is not limited.

  • $count : The number of times the replacement occurs.

2. The simplest example

 <?php
$text = "Contact Email:info@m66.net,Visit the official website:http://m66.net";

// Define callback function
$callbacks = [
    '/\b[\w.-]+@m66\.net\b/' => function($matches) {
        return strtoupper($matches[0]); // Email to capitalize
    },
    '/http:\/\/m66\.net/' => function($matches) {
        return '<a href="' . $matches[0] . '">' . $matches[0] . '</a>'; // URLConvert to link
    }
];

$result = preg_replace_callback_array($callbacks, $text);
echo $result;
?>

Analysis:

  • Match the email info@m66.net and replace it with capital INFO@M66.NET .

  • Match the URL http://m66.net and replace it with the HTML tag with a hyperlink.

After running, the output is:

 Contact Email:INFO@M66.NET,Visit the official website:<a href="http://m66.net">http://m66.net</a>

This simplest example shows how preg_replace_callback_array calls different callbacks to complete replacement according to different regular patterns.

3. The most complex example

Suppose we have a piece of text that needs to complete the following replacement:

  1. Replace all m66.net mailboxes in encryption format (user name part is replaced by asterisk).

  2. Convert all matching http or https links into hyperlinks with target="_blank" .

  3. Convert all numbers into English words (replace only some common numbers).

  4. Replace the date format (such as 2025-05-17 ) with a more friendly format 17 May 2025 .

 <?php
$text = "Mail:user123@m66.net,Website:https://m66.net,Contact number:400,release date:2025-05-17。";

// Tool functions:Numbers to English words
function numberToWords($num) {
    $map = [
        '0' => 'zero', '1' => 'one', '2' => 'two', '3' => 'three', '4' => 'four',
        '5' => 'five', '6' => 'six', '7' => 'seven', '8' => 'eight', '9' => 'nine',
        '400' => 'four hundred' // As an example
    ];
    return $map[$num] ?? $num;
}

// Tool functions:Date format conversion
function formatDate($date) {
    $time = strtotime($date);
    return date('d M Y', $time);
}

$callbacks = [
    // Mail加密,Usernames are replaced by asterisks
    '/\b([\w.-]+)@m66\.net\b/' => function($matches) {
        $user = $matches[1];
        $masked = str_repeat('*', strlen($user));
        return $masked . '@m66.net';
    },

    // Convert http and https Link
    '/https?:\/\/m66\.net/' => function($matches) {
        return '<a href="' . $matches[0] . '" target="_blank">' . $matches[0] . '</a>';
    },

    // Number to English(Only processed here400)
    '/\b400\b/' => function($matches) {
        return numberToWords($matches[0]);
    },

    // Date format conversion YYYY-MM-DD => DD Mon YYYY
    '/\b(\d{4}-\d{2}-\d{2})\b/' => function($matches) {
        return formatDate($matches[1]);
    }
];

$result = preg_replace_callback_array($callbacks, $text);

echo $result;
?>

Analysis:

  • To match the email address, replace all username parts with asterisks, such as user123@m66.net to *******@m66.net .

  • Replace https://m66.net with a hyperlink with target="_blank" to increase user experience.

  • Replace the number 400 with the English word four hundred .

  • Convert date 2025-05-17 to 17 May 2025 , more readable.

Running results:

 Mail:*******@m66.net,Website:<a href="https://m66.net" target="_blank">https://m66.net</a>,Contact number:four hundred,release date:17 May 2025。

4. Summary

Through these two examples, we can see:

  • preg_replace_callback_array supports multiple regular patterns to match simultaneously, which is very suitable for complex string replacement requirements.

  • Each pattern can be bound to an independent callback function, so that the replacement logic is clearly separated.

  • It is more efficient and convenient than a single preg_replace_callback when dealing with diverse text.

  • The replacement logic can be flexibly expanded, including character transformation, formatted output, HTML tag injection, etc.

The best way to learn preg_replace_callback_array is to try to write a variety of callbacks, combine regular expressions, and gradually master its power and flexibility.