CIDR Notation (IPv6) Regex for PHP
/^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}\/(?:1[01][0-9]|12[0-8]|[0-9]{1,2})$|^::(?:[fF]{4}(?::0{1,4})?:)?(?:25[0-5]|2[0-4][0-9]|[01]?[0-9]{1,2})(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9]{1,2})){3}\/(?:1[01][0-9]|12[0-8]|[0-9]{1,2})$|^(?:[0-9a-fA-F]{0,4}:){1,7}(?::[0-9a-fA-F]{0,4}){0,7}\/(?:1[01][0-9]|12[0-8]|[0-9]{1,2})$/iWhat this pattern does
This page provides a comprehensive, battle-tested regular expression for matching cidr notation (ipv6), 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 (IPv6)
// ReDoS-safe | RegexVault — Security > Network Security
define('CIDR_NOTATION_IPV6_PATTERN', '/^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}\\/(?:1[01][0-9]|12[0-8]|[0-9]{1,2})$|^::(?:[fF]{4}(?::0{1,4})?:)?(?:25[0-5]|2[0-4][0-9]|[01]?[0-9]{1,2})(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9]{1,2})){3}\\/(?:1[01][0-9]|12[0-8]|[0-9]{1,2})$|^(?:[0-9a-fA-F]{0,4}:){1,7}(?::[0-9a-fA-F]{0,4}){0,7}\\/(?:1[01][0-9]|12[0-8]|[0-9]{1,2})$/');
function validate_cidr_notation_ipv6(string $input): bool {
return (bool) preg_match(CIDR_NOTATION_IPV6_PATTERN, $input);
}
// Example
var_dump(validate_cidr_notation_ipv6("2001:db8::/32")); // bool(true)Test Cases
Matches (Valid) | Rejects (Invalid) |
|---|---|
2001:db8::/32 | 2001:db8::/129 |
::1/128 | 2001:db8:: |
fe80::/10 | ::1 |
::/0 | 192.168.0.0/24 |
2001:0db8:85a3:0000:0000:8a2e:0370:7334/64 | — |
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
IPv6 has multiple equivalent representations for the same address (:: compression, leading zero omission). Normalize to RFC 5952 canonical form before comparison or storage.
Technical Notes
IPv6 CIDR prefixes: /48 is common for ISP assignments, /64 for subnets (standard for SLAAC), /128 for single hosts. ::/0 is the IPv6 default route. fe80::/10 is link-local. ::1/128 is loopback.
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