<?php
class IDN {
// adapt bias for punycode algorithm
private static function punyAdapt(
$delta,
$numpoints,
$firsttime
) {
$delta = $firsttime ? $delta / 700 : $delta / 2;
$delta += $delta / $numpoints;
for ($k = 0; $delta > 455; $k += 36)
$delta = intval($delta / 35);
return $k + (36 * $delta) / ($delta + 38);
}
// make utf8 string from unicode codepoint number
private static function utf8($cp) {
if ($cp < 128) return chr($cp);
if ($cp < 2048)
return chr(192+($cp >> 6)).chr(128+($cp & 63));
if ($cp < 65536) return
chr(224+($cp >> 12)).
chr(128+(($cp >> 6) & 63)).
chr(128+($cp & 63));
if ($cp < 2097152) return
chr(240+($cp >> 18)).
chr(128+(($cp >> 12) & 63)).
chr(128+(($cp >> 6) & 63)).
chr(128+($cp & 63));
// it should never get here
}
// main decoding function
private static function decodePart($input) {
if (substr($input, 0, 4) !== 'xn--') {
return $input;
}
$input = substr($input, 4);
if (false !== $nonBasicCharsStart = strrpos($input, '-')) {
$output = str_split(substr($input, 0, $nonBasicCharsStart), 1);
$nonBasicChars = substr($input, $nonBasicCharsStart + 1);
} else {
$output = [];
$nonBasicChars = $input;
}
$n = 128;
$i = 0;
$bias = 72;
for ($j = 0, $l = strlen($nonBasicChars); $j < $l;) {
$oldi = $i;
$w = 1;
$k = 36;
while (true) {
if (!isset($nonBasicChars[$j])) {
return false;
}
$digit = ord($nonBasicChars[$j++]);
if ($digit >= 0x61 && $digit <= 0x7A) {
$digit -= 97;
} else if ($digit >= 0x30 && $digit <= 0x39) {
$digit -= 22;
} else {
return false;
}
$i += $digit * $w;
if ($k <= $bias) {
$t = 1;
} else if ($k >= $bias + 26) {
$t = 26;
} else {
$t = $k - $bias;
}
if ($digit < $t) {
break;
}
$w *= (int) (36 - $t);
$k += 36;
}
$c = count($output) + 1;
$bias = IDN::punyAdapt($i - $oldi, $c, $oldi === 0);
$n += (int)($i / $c);
$i %= $c;
array_splice($output, $i, 0, array(IDN::utf8($n)));
$i++;
}
return implode("", $output);
}
public static function decodeIDN($name) {
// split it, parse it and put it back together
return
implode(
".",
array_map("IDN::decodePart",explode(".",$name))
);
}
}
echo IDN::decodeIDN("xn---with-SUPER-MONKEYS-pc58ag80a8qai00g7n9n");
preferences:
57.1 ms | 402 KiB | 5 Q