Jump to content

How to identify if the input string is valid IP address format


bloodgoat

Recommended Posts

A little better would be a valid IPv4 address

 

Use this regex to match IP numbers with accurracy.

preg_match('/(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/', $IP);

Matches 0.0.0.0 through 255.255.255.255

 

Hate to burst your bubble MadTechie, but your regex will return true if the first and/or last node is greater than 255 and also it will validate if there are 4+ nodes.

 

I nonetheless did a benchmark, rigging it to always be a valid IP address and never be a valid IP address.  This function for all intents and purposes validates at worst, same speed as your pattern, at best, twice as fast (this function will return a false up to twice as fast as your regex).  Suppose it's not really fair comparing it to a broken regex, but I have a sneaking suspicion any regex you throw at it will give about the same results, with all the alternation that must  inevitably be used...

function isValidIP($ip) {
  $ip = explode('.',$ip);
  if (count($ip) != 4) return false;
  foreach ($ip as $node) {
    if (($node > 255) || ($node < 0) || !is_numeric($node))
      return false;
    }
  return true;
}

Hate to burst your bubble MadTechie, but your regex will return true if the first and/or last node is greater than 255 and also it will validate if there are 4+ nodes.

Not true it captures all 4, of course you could use ^ + $

the RegEx works fine.. can you post a IP it fails with !!

 

ie

if (preg_match('/\A(?:^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$)\Z/im', $ip)) {
echo "$ip passed";
} else {
echo "$ip failed";
}

253.26.54.4 = passed

255.235.12.2 = passed

256.12.23.45 = failed

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.