tags:

views:

60

answers:

2

I want to match a url link in wall post and replace this link with anchor tag, for this I use the regular expression below.

I would like the match 4 types of url:

  1. http://example.com
  2. https://example.com
  3. www.example.com
  4. example.com
preg_replace('@(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?)@',
             '<a href="$1">$1</a>', $subject);

This expression matches only first two types of url.

If I use this expression for match url pattern '@(www?([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?)@', then it only matches the third type of url pattern.

How can I match all four type of url pattern with a single regular expression?

A: 

I'd use a different regex to be honest. Like this one that Gruber posted last year

http://daringfireball.net/2009/11/liberal_regex_for_matching_urls

Nev Stokes
A: 

If you want to make that one work you need to make the "https?//" part optional, since you seem to have a fairly good grasp of regexps I won't show you, an excerise for the reader :)

But I generally agree with Nev, it's overly complicated for what it does.

dutt