REGEXVAULTv2.0
Web & Network/IPv4
Verified Safe

IPv4 Address (Strict 0–255) 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])$/

What this pattern does

Validating strict IPv4 addresses is a common requirement, and this PHP regex provides a robust solution. The pattern enforces that each octet falls within the 0–255 range, rejecting invalid addresses immediately. You can integrate this regex directly into your PHP applications for tasks like data sanitization or input validation within frameworks such as Symfony or CakePHP.

Php Implementation

Php
<?php
// IPv4 Address (Strict 0–255)
// ReDoS-safe | RegexVault — Web & Network > IPv4

define('IPV4_ADDRESS_STRICT_0255_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])$/');

function validate_ipv4_address_strict_0255(string $input): bool {
    return (bool) preg_match(IPV4_ADDRESS_STRICT_0255_PATTERN, $input);
}

// Example
var_dump(validate_ipv4_address_strict_0255("0.0.0.0")); // bool(true)

Test Cases

Matches (Valid)
Rejects (Invalid)
0.0.0.0256.1.1.1
192.168.1.1192.168.1
255.255.255.255192.168.1.1.1
10.0.0.1192.168.01.1
172.16.254.1not.an.ip.addr

When to use this pattern

In PHP, the risk of ReDoS stems from the potential for excessive backtracking, which can consume server resources and lead to denial-of-service vulnerabilities. Using a ReDoS-safe pattern like this one is especially critical in web applications where user-supplied data is processed. Without it, a maliciously crafted IP address could cause your application to hang or become unresponsive. This production-ready regex is thoroughly tested and verified for reliability.

Common Pitfalls

Using \d{1,3} instead of the strict alternation allows values like 999 or 256. Do not use [0-9]{1,3} — it accepts out-of-range octets.

Technical Notes

The alternation order in each octet group (25[0-5] first, then 2[0-4], then 1xx, then [1-9][0-9], then single digit) is critical for correctness. Reordering breaks range enforcement. Leading zeros are rejected because 01 does not match any branch.

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