Skip to content
PHP Logo

How can a callback function be implemented in preg_replace_callback to resolve the deprecated /e modifier issue in PHP?

The deprecated /e modifier in PHP's preg_replace function allowed for the evaluation of PHP code within the replacement string, which poses security risks. To resolve this issue, a callback function can be used instead to safely handle the replacements without executing PHP code.

php
$pattern = '/\b(\w+)\b/';
$replacement = function($matches) {
    return strtoupper($matches[0]);
};

$string = 'hello world';
$new_string = preg_replace_callback($pattern, $replacement, $string);

echo $new_string; // Output: HELLO WORLD