将一个汉字(GBK)转化成拼音

/**
* 将一个汉字(GBK)转化成拼音(暂不区分多音字)
*
*/

class Spell
{
protected static $_dat = '';
protected static $_fd = false;
function __construct()
{

}
function my_Getpy($pdat = '')
{
if ('' != $pdat)
self::$_dat = $pdat;
}

static function load($pdat = '')
{
if ('' == $pdat) {
$pdat = self::$_dat;
}
self::unload();
self::$_fd = @fopen($pdat, 'rb');
if (!self::$_fd) {
trigger_error("unable to load PinYin data file `$pdat`", E_USER_WARNING);
return false;
}
return true;
}

static function unload()
{
if (self::$_fd) {
@fclose(self::$_fd);
self::$_fd = false;
}
}

static function get($zh = '')
{
if (strlen($zh) != 2) {
trigger_error("`$zh` is not a valid GBK hanzi", E_USER_WARNING);
return false;
}
if (!self::$_fd && !self::load())
return false;
$high = ord($zh[0]) - 0x81;
$low = ord($zh[1]) - 0x40;

// 计算偏移位置
$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(self::$_fd, $off * 8, SEEK_SET);
$ret = fread(self::$_fd, 8);
$ret = unpack('a8py', $ret);
return $ret['py'];
}

function _my_Getpy()
{
self::_unload();
}
/**
* 优化转编码
* @param 字符串 $asc
*/
function _U2_Utf8_Gb($asc)
{
$string = '';
if ($asc < 0x80) {
$string .= $asc;
} elseif ($asc < 0x800) {
$string .= chr(0xC0 | $asc>>6);
$string .= chr(0x80 | $asc & 0x3F);
} elseif ($asc < 0x10000) {
$string .= chr(0xE0 | $asc>>12);
$string .= chr(0x80 | $asc>>6 & 0x3F);
$string .= chr(0x80 | $asc & 0x3F);
} elseif ($asc < 0x200000) {
$string .= chr(0xF0 | $asc>>18);
$string .= chr(0x80 | $asc>>12 & 0x3F);
$string .= chr(0x80 | $asc>>6 & 0x3F);
$string .= chr(0x80 | $asc & 0x3F);
}
$res = iconv('UTF-8', 'GBK//IGNORE', $string);
return $res;
}
/**
* 得到首字母
* @param 字符 $str
*/
static function getRes ($str = '')
{
//$str = self::_U2_Utf8_Gb($str);
self::$_dat = dirname(__FILE__).'/py.dat';
$len = strlen($str);
$ret = '';
for ($i = 0; $i < $len; $i++) {
if (ord($str[$i]) > 0x80) {
$pinyin = self::get(substr($str, $i, 2));
$ret .= ($pinyin ?substr($pinyin, 0, 1).'' : substr($str, $i, 2));
$i++;
} else {
$ret .= $str[$i];
}
}
self::unload();
$ret = strtoupper($ret);
return $ret;
}
}

你可能感兴趣的:(php函数)