What are the advantages of using preg_replace_callback over preg_replace for replacing URLs in PHP strings?

When replacing URLs in PHP strings, using preg_replace_callback allows for more flexibility and control over the replacement process compared to preg_replace. With preg_replace_callback, you can define a custom callback function to handle the replacement logic for each matched URL. This is especially useful when you need to perform dynamic replacements or complex transformations on the URLs before inserting them back into the string.

// Sample code demonstrating the use of preg_replace_callback to replace URLs in a string

$string = "Check out my website at https://www.example.com and my blog at http://blog.example.com";

// Define a custom callback function to replace URLs with anchor tags
function replaceUrlsWithLinks($matches) {
    $url = $matches[0];
    return "<a href='$url'>$url</a>";
}

// Use preg_replace_callback to replace URLs with anchor tags in the string
$replacedString = preg_replace_callback('/https?:\/\/\S+/', 'replaceUrlsWithLinks', $string);

echo $replacedString;