Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

validate url with regular expressions [duplicate]

Tags:

regex

php

I've gone through all possible ways for having the regular expression for the url validation, but I didn't get any.. what I need is the url can be like

google.com
http://google.com
https://google.com
http://www.google.com
https://www.google.com

but it should not allow if it is just google

finally the thing is the .extensions are mandatory

I've tried this /^[a-z0-9-]+(.[a-z0-9-]*)(.[a-z0-9-]*)$/

can anyone help me in this case..

like image 858
kumar Avatar asked May 08 '13 06:05

kumar


1 Answers

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

like image 194
Yogesh Suthar Avatar answered Oct 03 '22 03:10

Yogesh Suthar