CodexBloom - Programming Q&A Platform

Regex scenarios to Match IP Addresses with Optional Subnet Masks in PHP

👀 Views: 28 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-12
regex php validation PHP

I'm following best practices but I'm not sure how to approach I'm currently working on a PHP application where I need to validate IP addresses that may optionally include a subnet mask. I wrote a regex pattern that works for standard IPv4 addresses, but I'm struggling to incorporate the subnet mask functionality. My current regex looks like this: ```php $pattern = '/^(?:\d{1,3}\.){3}\d{1,3}(?:\/\d{1,2})?$/'; // Example IPs to test: $ips = ['192.168.1.1', '10.0.0.5/24', '172.16.0.1/16', '256.256.256.256', '192.168.1.1/33']; foreach ($ips as $ip) { if (preg_match($pattern, $ip)) { echo "$ip is valid\n"; } else { echo "$ip is NOT valid\n"; } } ``` I found that my regex fails to catch valid entries like `10.0.0.5/24` and incorrectly rejects `192.168.1.1/33` (which I expect to be invalid since subnet masks should be in the range 0-32). The output I get currently is: ``` 192.168.1.1 is valid 10.0.0.5/24 is NOT valid 172.16.0.1/16 is NOT valid 256.256.256.256 is NOT valid 192.168.1.1/33 is NOT valid ``` I suspect the scenario lies with how I'm handling the subnet part, particularly the range validation. Can anyone suggest a way to ensure the subnet mask part is validated correctly, while still maintaining the IP address validation? I'm using PHP 8.0 and have looked into other regex patterns but they seem overly complicated. Any insights or best practices would be greatly appreciated! What am I doing wrong?