标题:php采用UTF-8编码时候中文拼音排序 出处:沧海一粟 时间:Fri, 21 Nov 2008 14:01:11 +0000 作者:jed 地址:http://www.dzhope.com/post/487/ 内容: 因为我的记忆力严重不足,所以这几天写了一个UTF-8的备忘录,结果发现在UTF-8的编码下,mysql不能正确地排序,于是换到php里面用sort,继续失败……汗死……后来一想,可能是因为UTF-8的编码不是按照拼音来编码的,所以才会导致这个原因,另外貌似GBK的字库也不是完全按拼音排序的,"窦"字在GBK里面存在,但是却排在最后面,为了避免错乱,故在排序时把"窦"替换成同音字"豆",即可,于是写了这个排序函数……哎,弄了我一个晚上,结果就8行代码……无语了…… PHP代码 function name_cmp($a, $b) { $a = str_replace('窦', '豆', $a); $b = str_replace('窦', '豆', $b); $a = iconv('UTF-8', 'GBK', $a); $b = iconv('UTF-8', 'GBK', $b); $a = ereg_replace('^(a|an|the) ', '', strtolower($a)); $b = ereg_replace('^(a|an|the) ', '', strtolower($b)); return strcasecmp($a, $b); } usort($array, 'name_cmp'); 关于网上的mysql按拼音查询的两种说法: 1. 用ORDER BY BINARY(字段) ASC的方式查询数据库 实际上在纯UTF-8的环境下是实现不了了,只有用UTF-8的编码去保存GBK的字符之后才能这样使用,而且不能忘记替换像"窦"这种特殊的字哦…… 2. 在数据库中新建一个字段,保存汉字拼音,再利用该字段查询 这个方法在数据库里面看起来比较直观,不过同样需要把汉字转换成拼音,直接获得拼音的首字母还是不够的....... 在网上找了份代码,运行的还不错,不过需要下载一个字库文件: RAR压缩包: 下载该附件:http://www.bigasp.com.cn/Uploads/Files/Code/gbk拼音字库.rar 预览地址:http://www.bigasp.com.cn/extra/gbk2py 代码如下: PHP代码 class my_Getpy { var $_dat = 'py.dat'; var $_fd = false; function my_Getpy($pdat = '') { if ('' != $pdat) $this->_dat = $pdat; } function load($pdat = '') { if ('' == $pdat) $pdat = $this->_dat; $this->unload(); $this->_fd = @fopen($pdat, 'rb'); if (!$this->_fd) { trigger_error("unable to load PinYin data file `$pdat`", E_USER_WARNING); return false; } return true; } function unload() { if ($this->_fd) { @fclose($this->_fd); $this->_fd = false; } } function get($zh) { if (strlen($zh) != 2) { trigger_error("`$zh` is not a valid GBK hanzi", E_USER_WARNING); return false; } if (!$this->_fd && !$this->load()) return false; $high = ord($zh[0]) - 0x81; $low = ord($zh[1]) - 0x40; // 计算偏移位置 $nz = ($ord0 - 0x81); $off = ($high<<8) + $low - ($high * 0x40); // 判断 off 值 if ($off < 0) { trigger_error("`$zh` is not a valid GBK hanzi-2", E_USER_WARNING); return false; } fseek($this->_fd, $off * 8, SEEK_SET); $ret = fread($this->_fd, 8); $ret = unpack('a8py', $ret); return $ret['py']; } function _my_Getpy() { $this->_unload(); } } // demo 测试例子 ?> GBK码汉字转拼音

GBK码汉字转拼音

输入汉字试试:
0x80) { $xx = $py->get(substr($str, $i, 2)); $ret .= ($xx ? $xx . ' ' : substr($str, $i, 2)); $i++; } else { $ret .= $str[$i]; } } $py->unload(); echo "字串 `{$str}` 的拼音是: {$ret}\n"; } ?> Generated by Bo-blog 2.1.1 Release