1

I need to validate domain names using PHP.
Only this format should be allowed: google.com, subdomain.stack-overflow.org etc
It should only allow - (in case of special characters)

No other format should be allowed ex: http, https,?,/index.php,www. etc (none of these should be allowed).

Also i do not want to allow: localhost,mydomain.com

I have tried: FILTER_VALIDATE_URL but it accepts http etc.
I also tried something regular expression like this: [a-z0-9-]+(.[a-z0-9-]+)

But it is allowing ex: stackoverflow (without a .org).

How can I achieve that?

$urlparts = parse_url(filter_var($url, FILTER_SANITIZE_URL));
if(!isset($urlparts['host'])){
    $urlparts['host'] = $urlparts['path'];
}
showdev
  • 25,529
  • 35
  • 47
  • 67
sash
  • 85
  • 2
  • 10

1 Answers1

1

Your regular expression was nearly correct. Just the . is short for "any character", not just for ".". So, try this regex:

/([0-9a-z-]+\.)?[0-9a-z-]+\.[a-z]{2,7}/

Remember that new top level domains are introduced. They do not use latin characters. Take a look at http://many.at/idntlds/.

About excluding “mydomain.com”: You would have to check for this after applying the regular expression.

mynetx
  • 870
  • 7
  • 23
  • Thank you, i'm trying this. Please check question i have edited it , i want to allow subdomains like subdomain.stack-overflow.org also. Thanks a lot – sash Aug 20 '13 at 10:04
  • Want to allow sub-subdomains as well, like “user.server.domain.tld”? – mynetx Aug 20 '13 at 10:12
  • No i want to allow sub domains only. But the domain should not be localhost or mydomain.com – sash Aug 20 '13 at 10:16