GBK->拼音PHP类

类别:编程语言 点击:0 评论:0 推荐:
<?
/***********************************************************************
                       Written by caocao
                       [email protected]
                       http://nethermit.yeah.net
***********************************************************************/

class pinyin
{
    var $data;
    var $dataSpecial;
    var $tone;
    var $head;
    var $format;
    var $foot;
    function setTone($tone)
    {
        $this->tone=$tone;
    }
    function setFormat($head, $format, $foot)
    {
        $this->head=$head;
        $this->format=$format;
        $this->foot=$foot;
    }
    function render($str, $ascii=false)
    {
        if ($ascii)
            return str_replace("%1", $str, str_replace("%2", $str, $this->format));
        if (preg_match("/^".$str."([0-9a-zA-Z]+)/im", $this->data, $regs))
            $pinyin=$regs[1];
        else
            $pinyin=$str." ";
        return str_replace("%1", $str, str_replace("%2", $this->tone?$pinyin:substr($pinyin, 0, -1), $this->format));
    }
    function parse($str)
    {
        $output="";
        $length=strlen($str);
        $output.=$this->head;
        for ($i=0;$i<$length;++$i)
        {
            if ($i==$length-1)
            {
                $output.=$this->render($str[$i], true);
                break;
            }
            $code1=ord($str[$i]);
            $code2=ord($str[$i+1]);
            if ($code1==0x0D&&$code2==0x0A)
            {
                $output.=$this->foot;
                $output.=$this->head;
                ++$i;
            }
            else if ($code1>=0x81&&$code1<=0xFE&&$code2>=0x40&&$code2<=0xFE&&$code2!=0x7F)
            {
                $output.=$this->render($str[$i].$str[$i+1]);
                ++$i;
            }
            else
                $output.=$this->render($str[$i], true);
        }
        $output.=$this->foot;
        return $output;
    }
    function pinyin()
    {
        $this->tone=true;
        $this->head="<table border=0><tr align=center>";
        $this->format="<td>%2<br />%1</td>";
        $this->foot="</tr></table>";
        $this->data=file_get_contents("pinyin_data.php");
    }
}
?>

本文地址:http://com.8s8s.com/it/it26007.htm