$re = '/(?:^|\ |\n)(((?:(?:http(?:s)?\:)?(?:\/\/))|(?:\/\/))?(?:(?=[a-z0-9\-\.]{1,255}(?=\/|\ |$|\:|\n|\?|\,|\!))(?:(?:(?:[a-z0-9]{1}(?:[a-z0-9\-]{1,62})?\.){1,127})[a-z]{2,}(?:\.[a-z]{2})?))(?:[a-z0-9\/\-\_\%\?\&\!\$\'\,\(\)\*\.\+\=\;])*?)(?=$|\.(?=\ |$)|\:|\n|\ |\?(?=\ |$)|\,|\!)/i';
$str = 'I really like to go to google.com and google stuff.
<br>
I also like http://hercdev.io, both are pretty cool!
http://google.com
<br>
This is the url to an image: https://objects.dreamhost.com/herc-scripts/chicken_sombrero.gif
<br>
But this is the actual image: <img src="https://objects.dreamhost.com/herc-scripts/chicken_sombrero.gif" style="max-width: 100px;" />
<br>
Note that the url to the image in the <img> tag is unaffected. This is true for things that are already links also, like <a href="http://google.com" target="_blank">this.</a>';
$subst = "<a href=\"$1\">$1</a>";
$result = preg_replace($re, $subst, $str);
echo "The result of the substitution is ".$result;
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for PHP, please visit: http://php.net/manual/en/ref.pcre.php