zoukankan      html  css  js  c++  java
  • PHP

    php汉字转拼音

    php函数(由dedecms(dedecms/include/inc/inc_fun_funAdmin.php)的SpGetPinyin函数修改,dedecms的字典不太完全):

    <?php
    
        function pinyin($str, $ishead) {
            static $pinyins = array();
        
            $restr = '';
            $str = trim($str);
            $slen = strlen($str);
            if($slen < 2) {
                return $str;
            }
    
            if(count($pinyins) == 0) {
                $fp = fopen('pinyin.dic', 'r');
                while(!feof($fp)) {
                    $line = trim(fgets($fp));
                    $a2 = explode('`', $line);
                    isset($a2[1]) && $pinyins[$a2[0]] = $a2[1];
                }
                fclose($fp);
            }
            
            for($i=0; $i<$slen; $i++) {
                if(ord($str[$i])>0x80) {
                    $c = $str[$i].$str[$i+1];
                    $i++;
                    if(isset($pinyins[$c])) {
                        $restr.= ($ishead==0)?$pinyins[$c]:$pinyins[$c][0];
                    }else {
                        $restr .= "_";
                    }
                }else if( preg_match("/[a-z0-9]/i", $str[$i]) ) {
                    $restr .= $str[$i];
                }
                else {
                    $restr .= "_";
                }
            }
    
            return $restr;
        }
        
        //测试
        echo pinyin('舒熱佳隔热膜',1),'<br>'; 
        echo pinyin('舒熱佳隔热膜',0),'<br>'; 
        echo pinyin('鹦鹉',1),'<br>';  
        echo pinyin('鹦鹉',0),'<br>';  
        echo pinyin('眠之堡/依诺维绅/myside床垫',1),'<br>'; 
        echo pinyin('眠之堡/依诺维绅/myside床垫',0),'<br>';  
        
        /*结果:
        srjgrm
        shurejiageremo
        yw
        yingwu
        mzb_ynws_mysidecd
        mianzhibao_yinuoweishen_mysidechuangdian*/
    ?>

    包含的字典见附件:pinyin.rar/pinyin.dic (gbk)

    下载地址:https://files.cnblogs.com/luoyunshu/pinyin.rar

  • 相关阅读:
    中考 2020 游记
    CodeChef 2020 July Long Challenge 题解
    GDOI2020 游记
    AtCoder Grand Contest 044 题解
    ISIJ2020 不知道算不算游记
    WC2020 拿铁记
    UOJ Round 19 题解
    本博客采用 CC BY-NC-SA 4.0 进行许可
    [算法模版]回文树
    AddressSanitizer
  • 原文地址:https://www.cnblogs.com/luoyunshu/p/3824863.html
Copyright © 2011-2022 走看看