参照别人的PHP方法,封装了一个PHP简繁体转化的类。
其中包括一个配置文件、一个类文件。
配置文件:主要是简繁体对应的字体,可以手动的添加简繁体库
类文件:主要是两个function,一个提供简体转化为繁体,相应的另外一个就是繁体转化为简体。
这里的配置文件我就不解释了,可以看一下转化类的代码:
require_once "transfer_config.php";//读取简繁体配置文件 class Transfer { const ZH_ASCII_LOW = 224; //中文ASCII的最小值 const ZH_ASCII_HIGHT = 239; //中文ASCII的最大值 public static $utf8_gb2312; //类的变量,存储繁体 public static $utf8_big5; //类的变量,存储简体 public function __construct() { global $UTF8_GB2312; global $UTF8_BIG5; self::$utf8_gb2312 = $UTF8_GB2312; self::$utf8_big5 = $UTF8_BIG5; } public function cnToTw($string) { $traditional = ""; //繁体变量初始化 $length = strlen($string); //提取string字符串的ASCII码长度,注意一个中文字符对应于3位 $count = 0; while ($count < $length) { //获取$count位置上的ASCII值 $ascii = ord($string{$count}); if ($ascii >= self::ZH_ASCII_LOW && $ascii <= self::ZH_ASCII_HIGHT) { if (($temp = strpos(self::$utf8_gb2312, $string{$count} . $string{$count + 1} . $string{$count + 2})) !== false) { $traditional .= self::$utf8_big5{$temp} . self::$utf8_big5{$temp + 1} . self::$utf8_big5{$temp + 2}; $count += 3; continue; } } $traditional .= $string{$count++}; } return $traditional; } public function twToCn($string) { $simplified = ""; $length = strlen($string); $count = 0; while ($count < $length) { //获取$count位置上的ASCII值 $ascii = ord($string{$count}); if ($ascii >= self::ZH_ASCII_LOW && $ascii <= self::ZH_ASCII_HIGHT) { if (($temp = strpos(self::$utf8_big5, $string{$count} . $string{$count + 1} . $string{$count + 2})) !== false) { $simplified .= self::$utf8_gb2312{$temp} . self::$utf8_gb2312{$temp + 1} . self::$utf8_gb2312{$temp + 2}; $count += 3; continue; } } $simplified .= $string{$count++}; } return $simplified; } }
配有附件测试代码,需要的话可以下载使用哦亲!