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";
}
Your actual regex is :
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 :
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 :
PS : If you want to test your regex, this site is very cool : https://regex101.com/