How to replace text URLs and exclude URLs in HTML tags?

Viewed 6464

I need you help here.

I want to turn this:

sometext sometext http://www.somedomain.com/index.html sometext sometext

into:

sometext sometext <a href="http://somedoamai.com/index.html">www.somedomain.com/index.html</a> sometext sometext

I have managed it by using this regex:

preg_replace("#((http|https|ftp)://(\S*?\.\S*?))(\s|\;|\)|\]|\[|\{|\}|,|\"|'|:|\<|$|\.\s)#ie", "'<a href=\"$1\" target=\"_blank\">$1</a>$4'", $text);

The problem is it’s also replacing the img URL, for example:

sometext sometext <img src="http//domain.com/image.jpg"> sometext sometext

is turned into:

sometext sometext <img src="<a href="http//domain.com/image.jpg">domain.com/image.jpg</a>"> sometext sometext

Please help.

7 Answers

match a whitespace (\s) at the start and end of the url string, this will ensure that

"http://url.com" 

is not matched by

http://url.com 

is matched;

Related