PHP find urls in string and make links. If not already in the link
I want to find urls in strings where the link is not yet in the link
My current code:
$text = "http://www.google.com is a great website. Visit <a href='http://www.google.com' >http://google.com</a>"
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
if(preg_match($reg_exUrl, $text, $url)) {
$links = preg_replace($reg_exUrl, '<a href="'.$url[0].'" rel="nofollow">'.$url[0].'</a>', $_page['content']['external_links']);
}
The problem with this is that it returns the reference twice (this is what it returns):
<a href="http://www.google.com" rel="nofollow">http://www.google.com</a> is a great website. Visit <a href='<a href="http://www.google.com" rel="nofollow">http://www.google.com</a>' ><a href="http://www.google.com" rel="nofollow">http://www.google.com</a></a>
+3
source to share
1 answer
I made the assumption that the url you want to match will be followed by a space, punctuation, or at the end of a line. Of course, if there is something like <a href="site">http://url </a>
that, then it won't work. If you expect to run into this, first replace everything \s+</a>
with</a>
$text = "http://www.google.com is a great website. Visit <a href='http://www.google.com' >http://google.com</a>, and so is ftp://ftp.theweb.com";
$reg_exUrl = "/((http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3})([\s.,;\?\!]|$)/";
if (preg_match_all($reg_exUrl, $text, $matches)) {
foreach ($matches[0] as $i => $match) {
$text = str_replace(
$match,
'<a href="'.$matches[1][$i].'" rel="nofollow">'.$matches[1][$i].'</a>'.$matches[3][$i],
$text
);
}
}
Output:
http://www.google.com is a great site. Go to http://www.google.com '> http://google.com and so ftp://ftp.theweb.com
0
source to share