What is the purpose of using preg_replace with a function in the match pattern in PHP?

Using preg_replace with a function in the match pattern allows for more complex replacements based on the matched pattern. This is useful when you need to perform dynamic replacements or transformations on the matched strings. By defining a custom function to handle the replacements, you have more control over the output.

$text = "Hello, my name is John and I am 25 years old.";
$new_text = preg_replace_callback('/\b(\w{4})\b/', function($matches) {
    return strtoupper($matches[1]);
}, $text);

echo $new_text;