How can preg_replace_callback be utilized to achieve specific text replacement goals in PHP?

To achieve specific text replacement goals in PHP, preg_replace_callback can be utilized. This function allows for more complex replacements by using a callback function to process matches. By defining a custom callback function, you can manipulate the matched text in a dynamic way before replacing it in the original string.

$text = "Hello, [NAME]! How are you, [NAME]?";
$replacedText = preg_replace_callback('/\[NAME\]/', function($matches) {
    static $count = 0;
    $count++;
    return "John Doe" . $count;
}, $text);

echo $replacedText;