开发者

Regex to match an IP address [closed]

Closed. This question does not meet Stack O开发者_如何学Cverflow guidelines. It is not currently accepting answers.

Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist

Closed 9 years ago.

Improve this question

I am newbie with regex and I want to use preg_match function to find if a string is an IP address.

For example,

$string = "10.0.0.1";
preg_match($regex, $string);

should return true. So, what $regex should be?


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.

This is why IPv6 is necessary - an IPv4 address is only 32bits long and the internet is popular :)


/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/

should do for your example (which does contain a string that is not an IP address). And of course, it's only an IPv4 address.


/^(?:(?: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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜