GBK 转 UTF-8 (trans.php) :
#!/usr/bin/php <?php define('GBK', '/usr/share/i18n/charmaps/GBK.gz'); define('UTF8', '/usr/share/i18n/charmaps/UTF-8.gz'); define('INPUT_FILE', 't.txt'); define('OUTPUT_FILE', 'a.txt'); $source = file_get_contents(INPUT_FILE); $source_utf8 = ''; $len = strlen($source); for($i = 0; $i < $len; $i++) : if(ord($source{$i}) < 128) : $source_utf8 .= $source{$i}; continue; endif; $word_gbk = '/x'.base_convert(unpack('C', $source{$i})[1], 10, 16).'/x'.base_convert(unpack('C', $source{$i+1})[1], 10, 16); $i ++; $word_unicode = exec('gzip -dc '.GBK.' |awk \'/CJK/ { if ($2 == "'.$word_gbk.'") print $1}\''); $word_unicode = (int) base_convert(str_replace(array('<U', '>'), '', $word_unicode), 16, 10); for($j = 1; $line = exec('gzip -dc '.UTF8.' |grep "<CJK>"|sed -n '.$j.'p'); $j++) { list($unicode_wrap, $utf8_code) = explode(' ', $line); list($unicode_wrap_min, $unicode_wrap_max) = explode('..', $unicode_wrap); $unicode_wrap_min = (int) base_convert(str_replace(array('<U', '>'), '', $unicode_wrap_min), 16, 10); $unicode_wrap_max = (int) base_convert(str_replace(array('<U', '>'), '', $unicode_wrap_max), 16, 10); if($word_unicode > $unicode_wrap_min and $word_unicode < $unicode_wrap_max) break; } foreach(str_split($utf8_code, 4) as $key => $char) { if($key == 2) $source_utf8 .= pack('C', (int) base_convert(substr($char, 2, 2), 16, 10) + ($word_unicode - $unicode_wrap_min)); else $source_utf8 .= pack('C', (int) base_convert(substr($char, 2, 2), 16, 10)); } endfor; file_put_contents(OUTPUT_FILE, $source_utf8); ?>
测试文件内容 t.txt:
sdf啊4h海星kdi3大小k35
输出文件内容 a.txt:
sdf啊4h海星kdi3大小k35
执行命令: php ./trans.php
查看结果:hexdump -C t.txt && hexdump -C a.txt
00000000 73 64 66 b0 a1 34 68 ba a3 d0 c7 6b 64 69 33 b4 |sdf..4h....kdi3.|
00000010 f3 d0 a1 6b 33 35 |...k35|
00000016
00000000 73 64 66 e5 95 8a 34 68 e6 b5 b7 e6 98 9f 6b 64 |sdf...4h......kd|
00000010 69 33 e5 a4 a7 e5 b0 8f 6b 33 35 |i3......k35|
0000001b
utf-8 转 gbk 待续。。。