I wrote a simple function which takes a block of text, extracts urls from it, and replaces all urls with an <a href> tag around them.
E.g http://site.com should become <a href="http://site.com">http://site.com</a>
Code:
function parseUrls( $string )
{
$string = trim($string);
$pattern = '%\bhttp[s]?://[A-z0-9/\.\-_]+%i';
$replacement = '<a href="$1">$1</a>';
$string = preg_replace($pattern, $replacement, $string);
return $string;
}
However if I pass the following string as input:
hello https://google.com test http://test.com/something.html abc http://site.com
The output I get is:
hello <a href=""></a> test <a href=""></a> abc <a href=""></a>
I.e so the urls are being matched, but $replacement isn’t being applied correctly. May be my usage of $1 is wrong somehow?
What am I doing wrong?
You don’t have a capturing group that
$1would refer to.Use
$replacement = '<a href="$0" target="_BLANK">$0</a>';instead.Also, don’t use
A-zin your character class (it matches more than you think: there are some non-letter characters between ASCIIZanda).A-Zis enough since you’ve made it case-insensitive anyway.