REGEXVAULTv2.0
Web & Network/IPv4
Verified Safe

IPv4 with CIDR Notation Regex for PHP

/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\/(?:3[0-2]|[12][0-9]|[0-9])$/

What this pattern does

This PHP-ready regular expression precisely validates IPv4 addresses in CIDR notation, such as 192.168.1.1/32. The pattern ensures both address correctness (0-255 per octet) and prefix length validity (0-32). Incorporate this regex into any PHP project that requires reliable IP address parsing, such as input sanitization in a web form or configuring network settings within an application.

Php Implementation

Php
<?php
// IPv4 with CIDR Notation
// ReDoS-safe | RegexVault — Web & Network > IPv4

define('IPV4_WITH_CIDR_NOTATION_PATTERN', '/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\\/(?:3[0-2]|[12][0-9]|[0-9])$/');

function validate_ipv4_with_cidr_notation(string $input): bool {
    return (bool) preg_match(IPV4_WITH_CIDR_NOTATION_PATTERN, $input);
}

// Example
var_dump(validate_ipv4_with_cidr_notation("192.168.0.0/24")); // bool(true)

Test Cases

Matches (Valid)
Rejects (Invalid)
192.168.0.0/24192.168.1.1/33
10.0.0.0/8256.0.0.0/24
0.0.0.0/0192.168.1/24
255.255.255.255/32192.168.0.0/
172.16.0.0/12192.168.0.0

When to use this pattern

PHP's PCRE regex engine can be susceptible to catastrophic backtracking, a serious vulnerability when handling user-provided data. Without a ReDoS-safe pattern, a malicious actor could craft an input that consumes excessive resources, potentially leading to denial-of-service. This validated regex provides peace of mind when integrating IP address validation into frameworks like Symfony or Laravel. It's production-ready, minimizing the risk of unexpected behavior.

Common Pitfalls

Using [0-9]{1,2} for the prefix allows /99. Always use the bounded alternation.

Technical Notes

Prefix length alternatives: 3[0-2] covers 30–32, [12][0-9] covers 10–29, [0-9] covers 0–9. Combined this gives 0–32 exactly.

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