1

Possible Duplicate:
Regexp to check if an IP is valid

I'm not good with regex and I searched for this but all I can find is matching IP addresses that have white space before and after the numbers for example it matches this only:

Text before 192.168.1.1 Text after

How can I make it match any ip address, I don't want the IP I just want to know if a text has an IP, for example I want this to match too:

text before192.168.1.1text after

I tried these ones:

\b(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\b

^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$

and thanks in advance.

4

1 に答える 1

5
if (preg_match('/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/', $string, $match)) {
    if (filter_var($match[0], FILTER_VALIDATE_IP)) {
        // we have an IP
    }
}

Yes, you could construct a regex which would match 0-255 directly and all the other rules an IP must follow, but this is so much more straight forward.

于 2012-11-21T21:48:50.327 に答える