php 正则表达式匹配 IP 地址
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5865817/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Regex to match an IP address
提问by ibrahim
I am newbie with regex and I want to use preg_match
function to find if a string is an IP address.
我是正则表达式的新手,我想使用preg_match
函数来查找字符串是否为 IP 地址。
For example,
例如,
$string = "10.0.0.1";
preg_match($regex, $string);
should return true. So, what $regex
should be?
应该返回true。那么,$regex
应该是什么?
回答by alex
Don't use a regex when you don't need to :)
不需要时不要使用正则表达式:)
$valid = filter_var($string, FILTER_VALIDATE_IP);
Though if you really do want a regex...
虽然如果你真的想要一个正则表达式......
$valid = preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\z/', $string);
The regex however will only validate the format, the max for any octet is the max for an unsigned byte, or 255
.
然而,正则表达式只会验证格式,任何八位字节的最大值是无符号字节的最大值,或者255
.
This is why IPv6 is necessary - an IPv4 address is only 32bits long and the internet is popular :)
这就是为什么 IPv6 是必要的 - IPv4 地址只有 32 位长并且互联网很受欢迎:)
回答by Tim Pietzcker
/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/
should do for your example (which does contain a string that is notan IP address). And of course, it's only an IPv4 address.
应该为您的示例做(它确实包含一个不是IP 地址的字符串)。当然,它只是一个 IPv4 地址。
回答by HymanSparrow
/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/
This will check for the Perfect Range including if a Range is Higher than 255 from any of 4.
这将检查完美范围,包括范围是否高于 4 个中的任何一个的 255。