Regualr expression to check ip address with short mask

513 views Asked by At

I want to validate an IP address with mask, like this: 192.168.32.4/24 but I only found how to validate an IP without the mask: 192.168.32.4

This is my code:

$target = "192.168.34.12";

if (preg_match("/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/", $target)) {
    echo "correct";
} else {
    echo "incorrect";
}

Thanks in advance.

[Solved]

$target = "192.168.34.12/24";
$regex = "/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\/([1-9]|1[0-9]|2[0-4])$/";

if (preg_match($regex, $target)) {
    echo "correct";
} else {
    echo "incorrect";
}
2

There are 2 answers

3
pchmn On BEST ANSWER

Your actual regex is :

$regex = "/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/";

and it recognizes an IP like this : 192.168.0.150

If you want to recognize IP with mask (like 192.168.32.4/24) do this regex :

$regex = "/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\/([1-9]|1[0-9]|2[0-4])$/";

In this last regex I just add \/([1-9]|1[0-9]|2[0-4]). The \ is used to espace the /. Otherwise the regex would believe it's the end of itself. The last part ([1-9]|1[0-9]|2[0-4]) is to accept mask from 1 to 24 only.

And finally your code would be like this :

$target = "192.168.34.12/24";
$regex = "/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\/([1-9]|1[0-9]|2[0-4])$/";

if (preg_match($regex, $target)) {
    echo "correct";
} else {
    echo "incorrect";
}

PS : If you want to test your regex, this site is very cool : https://regex101.com/

2
Suraj On

Try this:

$target = "192.168.34.123";


if (preg_match("/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/",$target)) {
    echo "correct";
} else {
    echo "incorrect";
}