iTranslated by AI
The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🦔
[PHP] Identifying Characters in Legacy Encodings with Unsafe Round-trip Conversions
Some characters in legacy encodings change to different characters during round-trip conversion with Unicode.
For example, consider NEC and IBM platform-dependent characters. The approximation symbol meaning "nearly equal to" (≒, U+2252) is defined twice in Shift_JIS (0x81E0 and 0x8790). After a round-trip conversion, 0x8790 is replaced by 0x81E0.
var_dump(
"\x81\xE0" === roundtrip("\x87\x90", 'cp932')
);
function roundtrip($char, $enc) {
return mb_convert_encoding(mb_convert_encoding($char, 'utf-8', $enc), $enc, 'utf-8');
}
Let's examine all the characters that get replaced during round-trip conversion.
count_unsafe_chars('cp932');
function roundtrip($char, $enc) {
return mb_convert_encoding(mb_convert_encoding($char, 'utf-8', $enc), $enc, 'utf-8');
}
function tohexupper($char) {
return strtoupper(bin2hex($char));
}
function count_unsafe_chars($enc) {
$count = 0;
for ($cp = 0x1000; $cp < 0x10000; ++$cp) {
$c = chr($cp >> 8).chr($cp & 0xff);
if (!mb_check_encoding($c, $enc)) {
continue;
}
$ret = roundtrip($c, $enc);
if ($c !== $ret) {
echo '[', tohexupper($c), ' ', tohexupper($ret), ']';
++$count;
}
}
echo PHP_EOL, PHP_EOL;
echo $enc, PHP_EOL;
echo 'count:', $count, PHP_EOL;
}
Running this reveals that 398 characters were converted.
Discussion