使用通配符验证域的正则表达式
Regex to validate domains with wildcards
我正在 PHP 中的 DNS 面板上工作,我必须验证没有尾随点的 DNS 记录名称。这里有几个例子:
example.com - match
sub.example.com - match
sub.sub.example.com - match
*.example.com - match
*.sub.example.com - match
sub.*.example.com - no mach
sub*.example.com - no match
*sub.example.com - no match
我目前正在使用这个正则表达式,但问题是它不匹配通配符 (*):
^(?!\-)(?:[a-z\d\-]{0,62}[a-z\d]\.){1,126}(?!\d+)[a-z\d]{1,63}$
我不太擅长格式化正则表达式。实现这一目标的最佳方法是什么?谢谢!
我找到了一个使用正则表达式的解决方案,它不完全遵守域规则,但效果很好,所以如果您打算使用它,我建议您进行额外的检查:
^(\*\.)?([a-z\d][a-z\d-]*[a-z\d]\.)+[a-z]+$
通过PHP有更好的解决方法:
$tmp = $domain_to_check;
if(strpos($tmp, '*.') === 0){
$tmp = substr($tmp, 2);
}
if(filter_var('http://' . $tmp, FILTER_VALIDATE_URL)){
// The format is valid
}else{
// The format is invalid
}
我正在 PHP 中的 DNS 面板上工作,我必须验证没有尾随点的 DNS 记录名称。这里有几个例子:
example.com - match
sub.example.com - match
sub.sub.example.com - match
*.example.com - match
*.sub.example.com - match
sub.*.example.com - no mach
sub*.example.com - no match
*sub.example.com - no match
我目前正在使用这个正则表达式,但问题是它不匹配通配符 (*):
^(?!\-)(?:[a-z\d\-]{0,62}[a-z\d]\.){1,126}(?!\d+)[a-z\d]{1,63}$
我不太擅长格式化正则表达式。实现这一目标的最佳方法是什么?谢谢!
我找到了一个使用正则表达式的解决方案,它不完全遵守域规则,但效果很好,所以如果您打算使用它,我建议您进行额外的检查:
^(\*\.)?([a-z\d][a-z\d-]*[a-z\d]\.)+[a-z]+$
通过PHP有更好的解决方法:
$tmp = $domain_to_check;
if(strpos($tmp, '*.') === 0){
$tmp = substr($tmp, 2);
}
if(filter_var('http://' . $tmp, FILTER_VALIDATE_URL)){
// The format is valid
}else{
// The format is invalid
}