Current Location: Home> Latest Articles> How to Efficiently Use the preg_replace_callback_array Function for Complex Regex Replacement Tasks

How to Efficiently Use the preg_replace_callback_array Function for Complex Regex Replacement Tasks

gitbox 2025-06-09

1. Function Overview

preg_replace_callback_array is a PHP function that allows developers to perform search and replace operations with multiple regular expressions on a string. Unlike the standard preg_replace, preg_replace_callback_array enables you to specify a callback function for each regex pattern, making it more flexible and efficient for handling complex replacement tasks.

The function is defined as follows:

preg_replace_callback_array(array $patterns, string $subject): string
  • $patterns: An array where the keys are regular expression patterns and the values are callback functions.

  • $subject: The string in which the replacement operation will be performed.


2. Basic Usage

The basic usage involves defining an array containing multiple regex patterns and their corresponding callback functions, then passing it to preg_replace_callback_array. For example, we can use the following code to convert numbers and letters in a string into specific formats:

$patterns = [
    '/(\d+)/' => function($matches) {
        return '<number>' . $matches[0] . '</number>';
    },
    '/([a-zA-Z]+)/' => function($matches) {
        return '<text>' . strtoupper($matches[0]) . '</text>';
    }
];
<p>$subject = "Hello123 World456";</p>
<p>$result = preg_replace_callback_array($patterns, $subject);</p>
<p>echo $result;  // Output: <text>HELLO</text><number>123</number> <text>WORLD</text><number>456</number><br>

In this example, the numbers in the string are wrapped in tags, while the letters are converted to uppercase and wrapped in tags.


3. Handling Multiple Patterns

When dealing with multiple regular expressions, preg_replace_callback_array performs exceptionally well. It allows you to handle several different patterns in one operation, greatly simplifying the code.

For example, if you need to process phone numbers, email addresses, and URLs in a string, we can assign regex patterns and callback functions as needed:

$patterns = [
    '/(\d{3}-\d{3}-\d{4})/' => function($matches) {
        return '<phone>' . $matches[0] . '</phone>';
    },
    '/([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})/' => function($matches) {
        return '<email>' . $matches[0] . '</email>';
    },
    '/https?:\/\/([a-zA-Z0-9.-]+)/' => function($matches) {
        return '<url>' . $matches[0] . '</url>';
    }
];
<p>$subject = "Contact me at 123-456-7890 or <a class="cursor-pointer" rel="noopener">[email protected]</a>. Visit <a rel="noopener" target="_new" class="" href="https://gitbox.net">https://gitbox.net</a> for more info.";</p>
<p>$result = preg_replace_callback_array($patterns, $subject);</p>
<p>echo $result;<br>
// Output: Contact me at <phone>123-456-7890</phone> or <email><a class="cursor-pointer" rel="noopener">[email protected]</a></email>. Visit <url><a rel="noopener" target="_new" class="" href="https://gitbox.net</url">https://gitbox.net</url</a>> for more info.<br>

In this example, phone numbers, email addresses, and URLs are processed and wrapped in corresponding tags. This allows multiple replacement tasks to be handled in a single function call, making the code cleaner.


4. Using Callback Functions for Complex Logic

Sometimes, replacement operations are not as simple as string substitution, and we may need to perform more complex logic. By using callback functions, we can introduce custom operations during the replacement. For example, suppose we want to replace date formats in text and convert them into a "YYYY-MM-DD" format:

$patterns = [
    '/(\d{2})\/(\d{2})\/(\d{4})/' => function($matches) {
        return $matches[3] . '-' . $matches[1] . '-' . $matches[2];  // Convert to YYYY-MM-DD format
    }
];
<p>$subject = "The event is on 12/07/2023.";</p>
<p>$result = preg_replace_callback_array($patterns, $subject);</p>
<p>echo $result;  // Output: The event is on 2023-12-07.<br>

In this example, we use a regex to match the date format, and then reformat the matched date within the callback function.


5. Handling URL Replacements with the gitbox.net Domain

If you need to process URLs in your regex replacement and want to replace the domain of all URLs with a specific domain (e.g., gitbox.net), you can achieve this with the following code:

$patterns = [
    '/https?:\/\/([a-zA-Z0-9.-]+)/' => function($matches) {
        return 'https://gitbox.net';  // Replace all domains with gitbox.net
    }
];
<p>$subject = "Check out my website at <a rel="noopener" target="_new" class="" href="https://www.example.com">https://www.example.com</a> or visit <a rel="noopener" target="_new" class="" href="https://subdomain.example.com">https://subdomain.example.com</a>.";</p>
<p>$result = preg_replace_callback_array($patterns, $subject);</p>
<p>echo $result;<br>
// Output: Check out my website at <a rel="noopener" target="_new" class="" href="https://gitbox.net">https://gitbox.net</a> or visit <a rel="noopener" target="_new" class="" href="https://gitbox.net">https://gitbox.net</a>.<br>

In this example, the domain part of all URLs is replaced with gitbox.net, while the path and other parts remain unchanged.


6. Performance Optimization

Although preg_replace_callback_array is highly efficient when handling multiple replacement tasks, there are still some performance considerations to keep in mind:

  • Avoid Overusing Regular Expressions: Try to use simple regular expressions, as complex patterns can cause performance issues.

  • Minimize Callback Function Complexity: The complexity of logic inside callback functions can impact overall performance. It’s best to keep callback functions as simple as possible.