Here’s a small function in PHP 8.3 that reverses an IPv4 address:
<?php
function reverseIPv4(string $ip): string {
// Validate if the input is a valid IPv4 address
if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
throw new InvalidArgumentException("Invalid IPv4 address provided.");
}
// Split the IP into segments, reverse them, and join back
return implode('.', array_reverse(explode('.', $ip)));
}
// Example usage
try {
$originalIP = "192.168.1.1";
$reversedIP = reverseIPv4($originalIP);
echo "Original IP: $originalIP\n";
echo "Reversed IP: $reversedIP\n";
} catch (InvalidArgumentException $e) {
echo "Error: " . $e->getMessage();
}
?>
Explanation:
- Validation: The
filter_var
function checks if the input is a valid IPv4 address. - Splitting and Reversing: The
explode
function splits the IP by dots,array_reverse
reverses the segments, andimplode
joins them back into a string. - Exception Handling: If the input is not a valid IPv4 address, an exception is thrown to handle the error gracefully.
This ensures the function works safely and as expected.