最近项目有个需求,在一个中英文(包括阿拉伯数字0-9)的海量词库中,提取每一个词语的首字母:
gannicus——>G
自由自在——>Z
2B——>E
傻X——>S
private function getfirstchar($s0){<BR> $s=iconv('UTF-8','gb2312', $s0);<BR> if (ord($s0)>128) { //汉字开头<BR> $asc=ord($s{0})*256+ord($s{1})-65536;<BR> if($asc>=-20319 and $asc<=-20284)return "A";<BR> if($asc>=-20283 and $asc<=-19776)return "B";<BR> if($asc>=-19775 and $asc<=-19219)return "C";<BR> if($asc>=-19218 and $asc<=-18711)return "D";<BR> if($asc>=-18710 and $asc<=-18527)return "E"; <BR> if($asc>=-18526 and $asc<=-18240)return "F"; <BR> if($asc>=-18239 and $asc<=-17923)return "G"; <BR> if($asc>=-17922 and $asc<=-17418)return "I"; <BR> if($asc>=-17417 and $asc<=-16475)return "J"; <BR> if($asc>=-16474 and $asc<=-16213)return "K"; <BR> if($asc>=-16212 and $asc<=-15641)return "L"; <BR> if($asc>=-15640 and $asc<=-15166)return "M"; <BR> if($asc<strong>*本文来源gaodai#ma#com搞@代~码^网+</strong><strong>搞代gaodaima码</strong>>=-15165 and $asc<=-14923)return "N"; <BR> if($asc>=-14922 and $asc<=-14915)return "O"; <BR> if($asc>=-14914 and $asc<=-14631)return "P"; <BR> if($asc>=-14630 and $asc<=-14150)return "Q"; <BR> if($asc>=-14149 and $asc<=-14091)return "R"; <BR> if($asc>=-14090 and $asc<=-13319)return "S"; <BR> if($asc>=-13318 and $asc<=-12839)return "T"; <BR> if($asc>=-12838 and $asc<=-12557)return "W"; <BR> if($asc>=-12556 and $asc<=-11848)return "X"; <BR> if($asc>=-11847 and $asc<=-11056)return "Y"; <BR> if($asc>=-11055 and $asc<=-10247)return "Z"; <BR> }else if(ord($s)>=48 and ord($s)<=57){ //数字开头<BR> switch(iconv_substr($s,0,1,'utf-8'))<BR> {<BR> case 1:return "Y";<BR> case 2:return "E";<BR> case 3:return "S";<BR> case 4:return "S";<BR> case 5:return "W";<BR> case 6:return "L";<BR> case 7:return "Q";<BR> case 8:return "B";<BR> case 9:return "J";<BR> case 0:return "L";<BR> } <BR> }else if(ord($s)>=65 and ord($s)<=90){ //大写英文开头<BR> return substr($s,0,1);<BR> }else if(ord($s)>=97 and ord($s)<=122){ //小写英文开头<BR> return strtoupper(substr($s,0,1));<BR> }<BR> else<BR> {<BR> return iconv_substr($s0,0,1,'utf-8');//中英混合的词语,不适合上面的各种情况,因此直接提取首个字符即可<BR> }<br><br> }<BR>
遗留问题:仍有少量词语无法提取,如亘古不灭,的G 没有提取出来
最终效果如图: