<?php
function normalise_ip($address)
{
if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/', $address, $matches)) { // IPv4 address
$num = 0;
for ($i = 1; $i <= 4; $i++) {
$octet = (int) $matches[$i];
if ($octet > 255) {
return false;
}
$num |= $octet << ((4 - $i) * 8);
}
return sprintf('00000000000000000000ffff%04x', $num);
} else if (preg_match('/\[?((?:[0-9a-f]{1,4}:|::)+[0-9a-f]{1,4})]?/i', strtolower($address), $matches)) { // IPv6 address
$parts = explode(':', $matches[1]);
$numParts = count($parts);
if ($parts[0] === '') {
array_splice($parts, 0, 2, array_fill(0, 8 - ($numParts - 2), '0000'));
} else if ($parts[$numParts - 1] === '') {
echo "end\n";
array_splice($parts, $numParts - 2, 2, array_fill(0, 8 - ($numParts - 2), '0000'));
} else {
foreach ($parts as $i => $part) {
if ($part === '') {
array_splice($parts, $i, 1, array_fill(0, 8 - ($numParts - 1), '0000'));
}
}
}
foreach ($parts as &$part) {
$part = sprintf('%04s', $part);
}
return implode('', $parts);
} else { // invalid
return false;
}
}
echo normalise_ip('192.168.0.1') . "\n";
echo normalise_ip('::ffff:C0A8:0001') . "\n";
echo normalise_ip('::ffff:C0A8:1') . "\n";
echo normalise_ip('[::ffff:C0A8:0001]') . "\n";
echo normalise_ip('[C0A8:0001::]') . "\n";
preferences:
43.89 ms | 402 KiB | 5 Q