CIDR Notation (IPv4) Regex for PHP
/^(?:(?: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]?)\/(?:[0-9]|[12][0-9]|3[0-2])$/What this pattern does
This page provides a comprehensive, battle-tested regular expression for matching cidr notation (ipv4), ported and verified for PHP. In security-sensitive code, using an unverified regex can open the door to both false positives and denial-of-service attacks. The snippet below is ready to drop into your PHP project — whether you're validating in a Laravel validator, a WordPress plugin, or a standalone PHP script.
Php Implementation
<?php
// CIDR Notation (IPv4)
// ReDoS-safe | RegexVault — Security > Network Security
define('CIDR_NOTATION_IPV4_PATTERN', '/^(?:(?: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]?)\\/(?:[0-9]|[12][0-9]|3[0-2])$/');
function validate_cidr_notation_ipv4(string $input): bool {
return (bool) preg_match(CIDR_NOTATION_IPV4_PATTERN, $input);
}
// Example
var_dump(validate_cidr_notation_ipv4("192.168.1.0/24")); // bool(true)Test Cases
Matches (Valid) | Rejects (Invalid) |
|---|---|
192.168.1.0/24 | 192.168.1.0/33 |
10.0.0.0/8 | 192.168.1.0/-1 |
172.16.0.0/12 | 192.168.1.0 |
0.0.0.0/0 | 256.0.0.0/8 |
1.2.3.4/32 | 192.168.1.0/24/extra |
When to use this pattern
This pattern is drawn from the Security > Network Security category and carries a ReDoS-safe certification. That matters for PHP developers because especially relevant in PHP where PCRE backtracking limits can trigger silent failures on malicious input. RegexVault audits patterns against known backtracking attack vectors, ensuring you have the necessary context before using this regex in a high-stakes production environment.
Common Pitfalls
0.0.0.0/0 (any IP) in a security group rule exposes a service to the entire internet. 0.0.0.0/0 in outbound rules allows all outbound traffic. Review CIDR rules regularly in cloud security groups.
Technical Notes
/0 = all IPs (default route), /32 = single host. Subnets should have a host part of all zeros for canonical CIDR notation (192.168.1.0/24, not 192.168.1.5/24). Common in firewall rules, security groups, and IP allowlists.
Have a pattern that belongs in the vault?
Submit it for review — community-verified patterns get credited to your GitHub handle. Free submissions join the queue. Priority review available for $15.
Submit a Pattern