You can directly validate url using filter_var and FILTER_VALIDATE_URL

if (filter_var($url, FILTER_VALIDATE_URL) !== false)

Edit

With Regex

$subject = "http://www.google.com";
$pattern = "/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i";
preg_match($pattern, $subject, $matches);
print_r($matches);

Output

Array ( [0] => http://www.google.com )

Codepad

  • 8
Reply Report

Try this Expression

/[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/gi

It will aceept all the cases that you have mentioned above

  • 5
Reply Report
((https?:|[^.])\/\/w{0,3}[.]?google.[a-z]{2,4})|google.[a-z]{2,4}

It is not the prettiest but it works. I've checked with http://regexpal.com/

  • 1
Reply Report
      • 2
    • Let me propose several improvements. 1 you could use https? this will match both http or https, 2 you don't need to put the w in a character class, 3 {0,1} means ? so you can make it .?. Although this regex just works for this example, what if I had http://translate.google.com or http://google.fr ?
    • Yes you're right about some improvements. He wanted it for examples he gave so I wrote it for that examples. If he wants domain It can be easily added. I've answered what he wanted or what I thought he wanted :)

Warm tip !!!

This article is reproduced from Stack Exchange / Stack Overflow, please click

Trending Tags

Related Questions