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:
http://example.com
https://example.com
www.example.com
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?
I looked around and didn't see any that were exactly what I needed. I found this one that was close, so i modified it as follows:
check it out on debuggex.
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.
use this pattern .
hope that helpful .
I'd use a different regex to be honest. Like this one that Gruber posted in 2009:
or this updated version that Gruber posted in 2010 (thanks, @IMSoP):
My two cents (five years later!):
Hope it helps someone
A complete working example using Nev Stokes given link: