Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate URL with or without protocol

Tags:

regex

php

Hi I would like to validate this following urls, so they all would pass with or without http/www part in them as long as there is TLD present like .com, .net, .org etc..

Valid URLs Should Be:

http://www.domain.com
http://domain.com
https://www.domain.com
https://domain.com
www.domain.com
domain.com

To support long tlds:

http://www.domain.com.uk
http://domain.com.uk
https://www.domain.com.uk
https://domain.com.uk
www.domain.com.uk
domain.com.uk

To support dashes (-):

http://www.domain-here.com
http://domain-here.com
https://www.domain-here.com
https://domain-here.com
www.domain-here.com
domain-here.com

Also to support numbers in domains:

http://www.domain1-test-here.com
http://domain1-test-here.com
https://www.domain1-test-here.com
https://domain1-test-here.com
www.domain1-test-here.com
domain-here.com

Also maybe allow even IPs:

127.127.127.127

(but this is extra!)

Also allow dashes (-), forgot to mantion that =)

I've found many functions that validate one or another but not both at same time. If any one knows good regex for it, please share. Thank you for your help.

like image 996
Tux Avatar asked Dec 18 '12 05:12

Tux


2 Answers

For url validation perfect solution.

Above Answer is right but not work on all domains like .me, .it, .in

so please user below for url match:

$pattern = '/(?:https?:\/\/)?(?:[a-zA-Z0-9.-]+?\.(?:[a-zA-Z])|\d+\.\d+\.\d+\.\d+)/';

if(preg_match($pattern, "http://website.in"))
{
echo "valid";
}else{
echo "invalid";
}
like image 70
joni jerr Avatar answered Sep 22 '22 17:09

joni jerr


When you ignore the path part and look for the domain part only, a simple rule would be

(?:https?://)?(?:[a-zA-Z0-9.-]+?\.(?:com|net|org|gov|edu|mil)|\d+\.\d+\.\d+\.\d+)

If you want to support country TLDs as well you must either supply a complete (current) list or append |.. to the TLD part.

With preg_match you must wrap it between some delimiters

$pattern = ';(?:https?://)?(?:[a-zA-Z0-9.-]+?\.(?:com|net|org|gov|edu|mil)|\d+\.\d+\.\d+\.\d+);';
$index = preg_match($pattern, $url);

Usually, you use /. But in this case, slashes are part of the pattern, so I have chosen some other delimiter. Otherwise I must escape the slashes with \

$pattern = '/(?:https?:\/\/)?(?:[a-zA-Z0-9.-]+?\.(?:com|net|org|gov|edu|mil)|\d+\.\d+\.\d+\.\d+)/';
like image 33
Olaf Dietsche Avatar answered Sep 21 '22 17:09

Olaf Dietsche