You can directly validate url using filter_var and FILTER_VALIDATE_URL

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


With Regex

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


Array ( [0] => )


  • 8
Reply Report

Try this Expression


It will aceept all the cases that you have mentioned above

  • 5
Reply Report

It is not the prettiest but it works. I've checked with

  • 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 or ?
    • 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