0

i want to validate the domain name in php using preg_match

For example these are all valid:

https://www.google.com 
http://www.google.com 
www.google.com 
google.com 
google.com/ 
https://www.google.com.tr/search?dcr=0&source=hp&q=web+ui& 

i can validate following example only

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

$domain_validation = "/(?:http(s)?:\/\/)?(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+(?:[a-z]{2,63}|[a-z0-9]{2,59})?(?:\/)+$/i";
if(preg_match("$domain_validation", $inputDomainName)){
     $validSite = true;
}

and i want to validate this

google.com/ 
https://www.google.com.tr/search?dcr=0&source=hp&q=web+ui& 

Please help to solve

Gerrit Fries
  • 145
  • 1
  • 13
user3101664
  • 203
  • 1
  • 3
  • 16
  • 2
    What about [`filter_var`](http://php.net/manual/en/function.filter-var.php) With `FILTER_VALIDATE_URL `? See: [PHP validation/regex for URL](https://stackoverflow.com/questions/206059/php-validation-regex-for-url/207627#207627) – ficuscr Sep 22 '17 at 17:15

2 Answers2

1

Try this one. It should do exactly what you want.

$domain_validation = '/((http|https)\:\/\/)?[a-zA-Z0-9\.\/\?\:@\-_=#]+\.([a-zA-Z0-9\&\.\/\?\:@\-_=#])*/';
if(preg_match("$domain_validation", $inputDomainName)){
    $validSite = true;
}
Gerrit Fries
  • 145
  • 1
  • 13
1

You can try this function

function getDomain($url) {
  $pieces = parse_url($url);
  $domain = isset($pieces['host']) ? $pieces['host'] : '';
  if (preg_match('/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $domain, $regs)) {
    return $regs['domain'];
  }
  return false;
}

Above function return domain with extension

Example: It will return google.com if you pass any thing even with subdomain mail.google.com or any www.google.com/images/xyz

Then you pass any url to this function it returns you the domain with extension (.com, .net, .in whatever) and you can check with your inputdomain and validate simple.

Hope this helps

RamaKrishna
  • 219
  • 1
  • 8