欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

php汉字转拼音的示例

程序员文章站 2023-12-02 16:20:58
复制代码 代码如下:

复制代码 代码如下:

<?php
class helper_spell{
    public $spellarray = array();

    static public function getarray() {
        return unserialize(file_get_contents('pytable_without_tune.txt'));
    }
    /**
     * @desc 获取字符串的首字母
     * @param $string 要转换的字符串
     * @param $isone 是否取首字母
     * @param $upper 是否转换为大写
     * @return string
     *
     * 例如:getchinesefirstchar('我是作者') 首字符全部字母+小写
     * return "wo"
     *
     * 例如:getchinesefirstchar('我是作者',true) 首字符首字母+小写
     * return "w"
     *
     * 例如:getchinesefirstchar('我是作者',true,true) 首字符首字母+大写
     * return "w"
     *
     * 例如:getchinesefirstchar('我是作者',false,true) 首字符全部字母+大写
     * return "wo"
     */
    static public function getchinesefirstchar($string,$isone=false,$upper=false) {
        $spellarray = self::getarray();
        $str_arr = self::utf8_str_split($string,1); //将字符串拆分成数组

        if(preg_match('/^[\x{4e00}-\x{9fa5}]+$/u',$str_arr[0])) { //判断是否是汉字
            $chinese = $spellarray[$str_arr[0]];
            $result = $chinese[0];
        }else {
            $result = $str_arr[0];
        }

        $result = $isone ? substr($result,0,1) : $result;

        return $upper?strtoupper($result):$result;
    }

    /**
     * @desc 将字符串转换成拼音字符串
     * @param $string 汉字字符串
     * @param $upper 是否大写
     * @return string
     *
     * 例如:getchinesechar('我是作者'); 全部字符串+小写
     * return "wo shi zuo zhe"
     *
     * 例如:getchinesechar('我是作者',true); 首字母+小写
     * return "w s z z"
     *
     * 例如:getchinesechar('我是作者',true,true); 首字母+大写
     * return "w s z z"
     *
     * 例如:getchinesechar('我是作者',false,true); 首字母+大写
     * return "wo shi zuo zhe"
     */
    static public function getchinesechar($string,$isone=false,$upper=false) {
        global $spellarray;
        $str_arr = self::utf8_str_split($string,1); //将字符串拆分成数组
        $result = array();
        foreach($str_arr as $char)
        {
            if(preg_match('/^[\x{4e00}-\x{9fa5}]+$/u',$char))
            {
                $chinese = $spellarray[$char];
                $chinese  = $chinese[0];
            }else{
                $chinese=$char;
            }
            $chinese = $isone ? substr($chinese,0,1) : $chinese;
            $result[] = $upper ? strtoupper($chinese) : $chinese;
        }
        return implode(' ',$result);
    }
    /**
     * @desc 将字符串转换成数组
     * @param $str 要转换的数组
     * @param $split_len
     * @return array
     */
    private function utf8_str_split($str,$split_len=1) {

        if(!preg_match('/^[0-9]+$/', $split_len) || $split_len < 1) {
            return false;
        }

        $len = mb_strlen($str, 'utf-8');

        if ($len <= $split_len) {
            return array($str);
        }
        preg_match_all('/.{'.$split_len.'}|[^\x00]{1,'.$split_len.'}$/us', $str, $ar);

        return $ar[0];
    }
}