How to validate a domain name using Regex & Php?

前端 未结 6 655
失恋的感觉
失恋的感觉 2020-12-03 05:27

I want a solution to validate only domain names not full urls, The following example is what i\'m looking for:

domain.com -> true
domain.net -> true
do         


        
6条回答
  •  失恋的感觉
    2020-12-03 05:39

    In my case, domain name is considered as valid if the format is stackoverflow.com or xxx.stackoverflow.com

    So in addition to other stack answers, I have added checking for www. also.

    function isValidDomainName($domain) {
      if (filter_var(gethostbyname($domain), FILTER_VALIDATE_IP)) {
          return (preg_match('/^www./', $domain)) ? FALSE : TRUE;
      }
      return FALSE;
    }
    

    you can test the function with this code

        $domain = array("http://www.domain.com","http://www.domain.com/folder" ,"http://domain.com", "www.domain.com", "domain.com/subfolder", "domain.com","sub.domain.com");
        foreach ($domain as $v) {
            echo isValidDomainName($v) ? "{$v} is valid
    " : "{$v} is invalid
    "; }

提交回复
热议问题