Speed up development with full-stack environments for every branch.

Learn More

How to validate an IPv4 address using regular expressions [PHP and PCRE]

272 Runs 4232 Views 1809 Copies
Saved

Saved

gtsolutions 373

gtsolutions
published 4 years ago

<?php

/*
 * PHP PCRE - How to validate an IPv4 address using regular expressions
 */

function is_ipv4($ip)
{
    // The regular expression checks for any number between 0 and 255 beginning with a dot (repeated 3 times)
    // followed by another number between 0 and 255 at the end. The equivalent to an IPv4 address.
    //It does not allow leading zeros
    return (bool) preg_match('/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])'.
    '\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]?|[0-9])$/', $ip);
}


$ip = '127.0.0.1';
if(is_ipv4($ip))
    echo "$ip is a valid IPv4 address<br />";
else echo "$ip is NOT a valid IPv4 address<br />";

$ip = '127.00.0.1';
if(is_ipv4($ip))
    echo "$ip is a valid IPv4 address<br />";
else echo "$ip is NOT a valid IPv4 address<br />";
?>
Please login/signup to get access to the terminal.

Your session has timed out.

Dismiss (the page may not function properly).