How to validate a correct domain name and sub domain in php

会有一股神秘感。 提交于 2019-12-21 18:35:17

问题


How to remove www and validate a valid domain name.

Valid Domain

domain.com
subdomain.domain.com
sub-domain.domain.com

Invalid Domain

www.domain.com
www.subdomain.domain.com
http://www.domain.com/
http://www.subdomain.com/
www.domain.com/folder/

How the code?

$domain ='www.domain.com/folder/';
if() {
// validate here
}

回答1:


First, manually strip out the www. then just make sure it is in the form domain.tld or something.domain.tld

$domain = str_replace('www.','',$domain);

if(preg_match('/([a-zA-Z0-9\-_]+\.)?[a-zA-Z0-9\-_]+\.[a-zA-Z]{2,5}/',$domain)) //valid domain




回答2:


Take a look at http://framework.zend.com/apidoc/core/Zend_Validate/Zend_Validate_Hostname.html (Zend_Validate_Hostname) class. I think that you can use it outside of Zend Framework, with a minor tuning.




回答3:


$url = "http://stackoverflow.com/";
if (preg_match('/^(http|https|ftp)://([A-Z0-9][A-Z0-9_-]*(?:.[A-Z0-9][A-Z0-9_-]*)+):?(d+)?/?/i', $url)) {
    echo "Your url is ok.";
} else {
    echo "Wrong url.";
}


来源:https://stackoverflow.com/questions/3126556/how-to-validate-a-correct-domain-name-and-sub-domain-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!