How can the use of preg_replace_callback improve the functionality of PHP code?

When using preg_replace in PHP, sometimes we need more control over the replacement process, such as dynamically generating replacement values or performing complex operations. This is where preg_replace_callback comes in handy. By using preg_replace_callback, we can define a callback function that will be called for each match found by the regular expression, allowing us to manipulate the matches and replacements as needed.

$text = "Hello, {name}! Today is {day}.";
$replacements = [
    'name' => 'John',
    'day' => date('l')
];

$updated_text = preg_replace_callback('/\{(\w+)\}/', function($matches) use ($replacements) {
    $key = $matches[1];
    return isset($replacements[$key]) ? $replacements[$key] : $matches[0];
}, $text);

echo $updated_text;