验证域名PHP [英] Validate domain name PHP

查看:64
本文介绍了验证域名PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用PHP验证域名.
仅应允许以下格式:google.comsubdomain.stack-overflow.org
它应该只允许-(在特殊字符的情况下)

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)

不允许使用其他格式,例如:http, https,?,/index.php,www.等(均不得使用).

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

我也不想允许:localhostmydomain.com

我尝试过:FILTER_VALIDATE_URL但它接受http等.
我也尝试过这样的正则表达式:[a-z0-9-]+(.[a-z0-9-]+)

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-]+)

但是它允许ex:stackoverflow(不带.org).

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

我该如何实现?

$urlparts = parse_url(filter_var($url, FILTER_SANITIZE_URL));
if(!isset($urlparts['host'])){
    $urlparts['host'] = $urlparts['path'];
}

推荐答案

您的正则表达式几乎正确. .只是任何字符"的缩写,而不仅仅是."的缩写.因此,请尝试以下正则表达式:

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}/

请记住,引入了新的顶级域.他们不使用拉丁字符.看看 http://many.at/idntlds/.

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

关于排除"mydomain.com":您必须在应用正则表达式后进行检查.

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

这篇关于验证域名PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆