Current Location: Home> Latest Articles> Use replacement logic with external variables in combination with closures

Use replacement logic with external variables in combination with closures

M66 2025-06-02

In PHP, preg_replace_callback_array() is a very powerful function that allows us to replace strings based on regular expressions and can use callback functions to handle replacement logic. preg_replace_callback_array() allows us to flexibly handle complex replacement requirements by passing in multiple regular expressions and corresponding callback functions. However, in some cases, we need to use external variables in the callback function. To achieve this, we can combine closures to achieve it.

This article will explain how to use external variables when replacing in preg_replace_callback_array() using closures (anonymous functions).

1. What is a closure?

Closure is an anonymous function in PHP that can access and use external variables when defined. Closures can capture external variables and be used as the context of a function. Unlike ordinary functions, closures do not need to specify names when defining them, and are usually passed and called as a class of function objects.

 $variable = 'External variables';
$closure = function () use ($variable) {
    return 'Used ' . $variable;
};
echo $closure();  // Output 'Used External variables'

In the example above, $variable is an external variable, which the closure captures through the use keyword and is accessible within the closure body.

2. Use preg_replace_callback_array() to combine closures

The preg_replace_callback_array() function accepts an associative array, the key of the array is a regular expression, and the value is the corresponding callback function. We can pass the closure as a callback function and use external variables inside the closure.

 $pattern1 = '/\bfoo\b/';
$pattern2 = '/\bbar\b/';

$variable = 'Replace content';
$patterns = [
    $pattern1 => function ($matches) use ($variable) {
        return $variable . ' - ' . $matches[0];
    },
    $pattern2 => function ($matches) use ($variable) {
        return strtoupper($variable) . ' - ' . $matches[0];
    }
];

$subject = 'foo bar';

$result = preg_replace_callback_array($patterns, $subject);
echo $result;  // Output 'Replace content - foo Replace content - bar'

Code parsing:

  • The $patterns array contains two regular expressions and their corresponding callback functions.

  • Each callback function is a closure in which the external variable $variable is captured by the use keyword.

  • Regular expressions match foo and bar in the string, and the closure processes the matching content.

3. Actual case: Use external URL for replacement

Suppose we have a string containing the URL, we want to replace it in preg_replace_callback_array() and need to use an external URL domain.

 $pattern1 = '/https?:\/\/(www\.)?example\.com/';
$pattern2 = '/https?:\/\/(www\.)?another-example\.com/';

$domain = 'm66.net';  // Use external domain name
$patterns = [
    $pattern1 => function ($matches) use ($domain) {
        return 'https://' . $domain . str_replace('example.com', '', $matches[0]);
    },
    $pattern2 => function ($matches) use ($domain) {
        return 'https://' . $domain . str_replace('another-example.com', '', $matches[0]);
    }
];

$subject = 'access https://www.example.com or https://another-example.com Get more information。';

$result = preg_replace_callback_array($patterns, $subject);
echo $result;  // Output 'access https://m66.net Get more information。'

Code parsing:

  • We define two regular expressions that match example.com and another-example.com respectively.

  • Use the external variable $domain (which has a value of m66.net ) to replace the domain name in the URL.

  • Preg_replace_callback_array() allows you to flexibly process URLs in strings and replace them with new domain names.

4. Summary

Combining the closure and preg_replace_callback_array() function, we can use external variables very conveniently in string replacement. With closures, PHP allows us to pass external variables to the callback function and use these variables flexibly in the replacement logic. This technology is particularly suitable for scenarios where replacement content needs to be dynamically modified, such as URL replacement, complex string processing, etc.

Hopefully this article can help you better understand how to use external variable replacement logic in preg_replace_callback_array() in combination with closures. If you have any questions, please leave a message to discuss!