I want to match a URL link in a wall post and replace this link with anchor tag. For this I use the regular expression below.
I would like the match four 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 matching a URL pattern,
'@(www?([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?)@'
, it only matches the third type of URL pattern.
How can I match all four typeS of URL patternS with a single regular expression?
@:%_\+~#= , to match the domain/sub domain name.
Checking information entered by users into a form is referred to as form validation. There are many different forms of validation, but the basic pattern match function in PHP is eregi , which stands for “evaluate regular expression, case insensitive”.
Using preg_replace() The preg_replace() function will replace all of the matches of the pattern in a string with another string.
A complete working example using Nev Stokes' given link:
public function clickableUrls($html){
return $result = preg_replace(
'%\b(([\w-]+://?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/)))%s',
'<a href="$1">$1</a>',
$html
);
}
I'd use a different regex to be honest. Like this one that Gruber posted in 2009:
\b(([\w-]+://?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/)))
Or this updated version that Gruber posted in 2010 (thanks, @IMSoP):
(?i)\b((?:[a-z][\w-]+:(?:/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With