What are best practices for replacing URLs in a string using regular expressions in PHP?

When replacing URLs in a string using regular expressions in PHP, it is important to use a regex pattern that accurately matches URLs while also considering various URL formats. One common approach is to use the preg_replace function with a regex pattern that captures URLs and replace them with the desired replacement text.

<?php
$string = "Check out my website at https://www.example.com for more information.";
$pattern = '/(https?:\/\/)?(www\.)?([a-zA-Z0-9-]+)\.([a-zA-Z]{2,6})(\/\S*)?/';
$replacement = '<a href="$0" target="_blank">$0</a>';

$newString = preg_replace($pattern, $replacement, $string);

echo $newString;
?>