Regex to match an IP address [closed]

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 🙂

Leave a Comment