$re = '~(?<!(?:"|\'|=))((?:http(?:s)?://)(?:www\.)?[-A-Z0-9.]+(?:\.com)[-A-Z0-9_./]?(?:[-A-Z0-9#?/]+)?)~i';
$str = '<img src="http://somelink.com/img.jpg"> http://somelink.com
http://www.example.com
http://example.com/
<a href="http://www.google.com">Google</a>
https://www.example.com/seconday/somepage#hashes?parameters
https://www.example.com/seconday/
<link rel="stylesheet" type="text/css" href="http://www.domain.com/style.css" />
http://www.example.com/seconday
<script type="text/javascript" src="http://domain.com/includes/javscript.js"></script>
http://example.com/seconday
http://example.com/seconday/';
$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