PHP 正则表达式允许 "a-z" & "1-9" & "-" & 最少一个或最多两个 "."字符之间
PHP Regular Expression allow "a-z" & "1-9" & "-" & minimum one or maximum two "." between chars
我需要一个允许 "a-z" & "A-Z" & "-" & "."
的 PHP 正则表达式
- “。”允许使用最少 1 次和最多 2 次,而不是一起使用 ".."
- "-"可以多次使用但不能同时使用"--"且不能在后面使用
最后一个点“.”
换句话说,我想验证域名或子域名,例如:
my-domain.com 或 sub.my-domain.com
例如:my--domain.com 或 my-domain.com-net 或 my-domain-.com 等必须 return false.
if (!preg_match('/^[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9]\.[a-zA-Z]{2,}$/', $odomain)) {
//do something
}
如果您确定域和 TLD 不包含 Unicode 字符,您可能想尝试:
(?i)^[a-z\d]+([.-][a-z\d]+)*\.[a-z]+$
这也匹配 user.sub.domain.com
(忽略我认为无效的第一条规则)
PHP代码:
preg_match('/^[a-z\d]+([.-][a-z\d]+)*\.[a-z]+$/i', $domain);
下班后改进正则表达式并认为它运行良好:
/^(?!\-)(?:[a-zA-Z\d\-]{0,62}[a-zA-Z\d]\.){1,126}(?!\d+)[a-zA-Z\d]{1,63}$/
使用以下内容
[a-zA-Z0-9](-?[a-zA-Z0-9])*(\.[a-zA-Z0-9](-?[a-zA-Z0-9])*)+
见demo for details. Note that in the examples you post, my--domain.com or my-domain.com-net or my-domain-.com do have valid domain names, as shown in the demo。
编辑
修改后RFC-1035 I've seen that the requirement you post to disallow to adjacent -
chars is not valid, as it is perfectly valid to use two hyphens together, with care they don't get to the sides. So the edited regexp应该是:
[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])*(\.[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])*)+
我需要一个允许 "a-z" & "A-Z" & "-" & "."
的 PHP 正则表达式- “。”允许使用最少 1 次和最多 2 次,而不是一起使用 ".."
- "-"可以多次使用但不能同时使用"--"且不能在后面使用 最后一个点“.”
换句话说,我想验证域名或子域名,例如:
my-domain.com 或 sub.my-domain.com
例如:my--domain.com 或 my-domain.com-net 或 my-domain-.com 等必须 return false.
if (!preg_match('/^[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9]\.[a-zA-Z]{2,}$/', $odomain)) {
//do something
}
如果您确定域和 TLD 不包含 Unicode 字符,您可能想尝试:
(?i)^[a-z\d]+([.-][a-z\d]+)*\.[a-z]+$
这也匹配 user.sub.domain.com
(忽略我认为无效的第一条规则)
PHP代码:
preg_match('/^[a-z\d]+([.-][a-z\d]+)*\.[a-z]+$/i', $domain);
下班后改进正则表达式并认为它运行良好:
/^(?!\-)(?:[a-zA-Z\d\-]{0,62}[a-zA-Z\d]\.){1,126}(?!\d+)[a-zA-Z\d]{1,63}$/
使用以下内容
[a-zA-Z0-9](-?[a-zA-Z0-9])*(\.[a-zA-Z0-9](-?[a-zA-Z0-9])*)+
见demo for details. Note that in the examples you post, my--domain.com or my-domain.com-net or my-domain-.com do have valid domain names, as shown in the demo。
编辑
修改后RFC-1035 I've seen that the requirement you post to disallow to adjacent -
chars is not valid, as it is perfectly valid to use two hyphens together, with care they don't get to the sides. So the edited regexp应该是:
[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])*(\.[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])*)+