有一堆用cp1251 charset创建的旧网站。我被要求通过实现对用户输入的非cp1251符号的支持来增强其功能。将所有内容转换为utf-8有点为时已晚,因为有许多旧的无证文件依赖于旧的字符集,所以我想出了将所有“非标准”符号转换为HTML实体的想法。我为这项任务写了一堂课。它将UTF-8转换为cp1251和HTML实体,反之亦然。你怎么看待这件事?将其应用于输入后可能会出现哪些问题?还是有更好的方法吗?
class UTFire
{
/*
* This will exclude cp1251 symbols from encoding
*/
static $convmap = array(
0x0080, 0x009f, 0, 0xffff,
0x00a1, 0x00a3, 0, 0xffff,
0x00a5, 0x00a5, 0, 0xffff,
0x00a8, 0x00a8, 0, 0xffff,
0x00aa, 0x00aa, 0, 0xffff,
0x00af, 0x00af, 0, 0xffff,
0x00b2, 0x00b4, 0, 0xffff,
0x00b8, 0x00ba, 0, 0xffff,
0x00bc, 0x0400, 0, 0xffff,
0x040d, 0x040d, 0, 0xffff,
0x0450, 0x0450, 0, 0xffff,
0x045d, 0x045d, 0, 0xffff,
0x0460, 0x048f, 0, 0xffff,
0x0492, 0x2012, 0, 0xffff,
0x2015, 0x2017, 0, 0xffff,
0x201b, 0x201b, 0, 0xffff,
0x201f, 0x201f, 0, 0xffff,
0x2023, 0x2025, 0, 0xffff,
0x2027, 0x202f, 0, 0xffff,
0x2031, 0x2038, 0, 0xffff,
0x203b, 0x20ab, 0, 0xffff,
0x20ad, 0x2115, 0, 0xffff,
0x2117, 0x2121, 0, 0xffff,
0x2123, 0xffff, 0, 0xffff,
);
// Detect if input contains UTF-8 chars
static function isUTF8($str) {
return preg_match('//u', $str);
}
// Forward conversion
static function fwd($str) {
if(static::isUTF8($str)) {
$str = mb_encode_numericentity($str, static::$convmap, 'UTF-8');
$str = iconv('UTF-8', 'windows-1251//IGNORE', $str);
}
return $str;
}
// Backward conversion
static function bck($str) {
if(!static::isUTF8($str)) {
$str = iconv('windows-1251', 'UTF-8//IGNORE', $str);
$str = mb_decode_numericentity($str, static::$convmap, 'UTF-8');
}
return $str;
}
}