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.

Community
  • 1
  • 1
Pierre
  • 12,468
  • 6
  • 44
  • 63
  • 1
    why not show us that regexp that *almost* does what you want? – Lee Nov 21 '12 at 21:45
  • http://stackoverflow.com/questions/106179/regular-expression-to-match-hostname-or-ip-address – Lee Nov 21 '12 at 21:47
  • remove the `\b` from the beginning and end. In the second case, remove the `^` from the beginning, and remove the `$` from the end. – Lee Nov 21 '12 at 21:49

1 Answers1

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.

deceze
  • 510,633
  • 85
  • 743
  • 889