PHP
Validating and Extracting IPv4 Addresses
Use a robust regular expression in PHP to both validate if a string is a valid IPv4 address and extract it from a larger text.
<?php
function validateAndExtractIPv4(string $text): ?string {
// A simple regex for IPv4 address. Does not validate full octet range (0-255) for all segments.
// For full validation, a more complex regex or dedicated function is needed.
// This targets the common dotted-decimal format.
$regex = '/\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b/';
if (preg_match($regex, $text, $matches)) {
// A more robust check for 0-255 range per octet
$ip = $matches[0];
$octets = explode('.', $ip);
foreach ($octets as $octet) {
if ((int)$octet < 0 || (int)$octet > 255) {
return null; // Not a valid IPv4 despite basic regex match
}
}
return $ip;
}
return null;
}
$ip_text1 = "Server IP is 192.168.1.100 for testing.";
$ip_text2 = "Invalid IP like 999.0.0.1 or 10.0.0.256";
$ip_text3 = "No IP here.";
echo "IP 1: " . (validateAndExtractIPv4($ip_text1) ?? "Not found/invalid") . "
";
echo "IP 2: " . (validateAndExtractIPv4($ip_text2) ?? "Not found/invalid") . "
";
echo "IP 3: " . (validateAndExtractIPv4($ip_text3) ?? "Not found/invalid") . "
";
?>
How it works: This PHP function uses `preg_match` with a regex `/\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b/` to find patterns resembling IPv4 addresses. The `\b` word boundaries ensure whole IPs are matched. After a basic match, it performs an additional check by exploding the string into octets and verifying each is within the 0-255 range, providing more robust validation beyond just the regex pattern.