验证 IP 地址的特殊形式
我遇到了一个奇怪的 IP,它的八位字节中有多余的零值。是否有办法正确验证其作为 IP 或使用正则表达式删除那些多余的零?
示例如下: 218.064.215.239(注意第二个八位位组“064”处的额外零)。
我确实有一个有效的 IP 验证函数,但由于正则表达式的性质无法接受额外的零,因此它无法正确验证该 Ip。以下是 PHP 代码:
function valid_ip($ip) {
return preg_match("/^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])" .
"(\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}$/", $ip);
}
感谢您提前提供的任何帮助! :D
I have encountered a strange IP which has redundant zero values among the octets. Is there anyway to properly validate this as an IP or use regular expression to remove those redundant zeroes?
example is of follows:
218.064.215.239 (take note of the extra zero at the second octet "064").
I do have one working IP validation function but it will not validiate this Ip properly due to the nature of the regular expression unable to accept that extra zero. Following is the code in PHP:
function valid_ip($ip) {
return preg_match("/^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])" .
"(\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}$/", $ip);
}
thanks for any help in advance peeps! :D
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
这将纠正它们:
This will correct them:
您必须像这样接受零:
在 rubular.com 上使用此正则表达式。
我添加的
0?
匹配零次或一次出现的0
。例如,0?[1-9][0-9]
会匹配010
和10
。You have to accept the zero like this:
Play with this regular expression on rubular.com.
The
0?
I added matches zero or one occurence of0
. So0?[1-9][0-9]
for example matches both010
and10
for example.将出现的
|1
更改为|[01]
。不过,您确定这不应该被解释为八进制数吗?一些解析器会这样做。Change the bare
|1
occurrences to|[01]
. Are you sure this is not supposed to be interpreted as an octal number, though? Some resolvers do that.使用 ip2long()。
Use ip2long().
您应该弄清楚这些额外的零来自哪里。那些前导零不能被删除。在大多数平台上,它们意味着八位位组是八进制形式而不是十进制。即:八进制
064
等于十进制52
。You should figure out where those extra zeroes are coming from. Those leading zeroes can't be just dropped. On most platforms they mean that the octet is in octal form instead of decimal. That is:
064
octal equals52
decimal.你自己也去尝试一下吗?这真的很简单。
|1[0-9][0-9]|
匹配 100-199,因为您现在想要匹配 000-199(如上所述,它是 200-155),您只需要做1
为1
或0
的集合。可以将其重构(允许前导零)为:
或者删除这些不需要的零:
Did you have a go yourself? It's really quite simple.
|1[0-9][0-9]|
matches 100-199, as you are now wanting to match 000-199 (as above that it is 200-155) you just need to make a set for the1
to be1
or0
.And that can be refactored down (allowing leading zeroes) to:
Or to strip these unneeded zeros: