Replace hyperlinks in content with regular expressions

I have a line containing the contents of a user's blog. If they include the following:

www.google.com http://google.com http://www.google.com 

on my blog, I want PHP to replace these occurrences with a real hyperlink, but keep the original substring (i.e. not change www.google.com to http://www.google.com ).

Does anyone know how I can do this with PHP and regular expressions? I tried this:

 echo preg_replace('/((www|http:\/\/)[^ ]+)/', '<a href="$1" target="_blank">$1</a>', $content); 

But this will succeed only if you end the connection with a space. Failed to complete it with a comma or full stop.

+4
source share
2 answers
 preg_replace('/\b(?:(http(s?):\/\/)|(?=www\.))(\S+)/is', '<a href="http$2://$3" target="_blank">$1$3</a>', $content); 
+3
source
 $pattern = '/<a (.*?)href=[\"\'](.*?)\/\/(.*?)[\"\'](.*?)>(.*?)<\/a>/i'; $new_content = preg_replace($pattern, '$5', $content); 
0
source

All Articles