php獲取漢字首字母的函式

2022-09-28 21:51:21 字數 2328 閱讀 8581

網上的方法有不少,都是一樣的原理,按照需求,做了一下版本的class類檔案,主要功能是:功能明確,易於修改維護和擴充套件; 英文的字串:不變返回(包括數字);中文字串:返回拼音首字元; 中英混合串: 返回拼音首字元和英文。該演算法採用了二分法查詢,修復了之前字母z讀取成y的錯誤。好東西要,故在此留下印記,以供後人考證!

複製** **如下:

php

/*** modified by @ 2013-05-07

* 修復二分法查詢方法

* 漢字拼音首字母工具類

*  注: 英文的字串:不變返回(包括數字)    eg .abc123 => abc123

*      中文字串:返回拼音首字元        eg. 測試字串 => cszfc

*      中英混合串: 返回拼音首字元和英文   eg. 我i我j => wiwj

*  eg.

*  $py = new str2py();

*  $result = $py->getinitials('啊吧才的餓飛就好i就看了嗎你哦平去人是他uv我想一在');

*/class str2py

/*** 中文字串 substr

** @param string $str

* @param int    $start

* @param int    $len

* @return string

*/private function _msubstr ($str, $start, $len)

if ( ord(substr($str, $i, 1)) > 129 ) $i++;

}return $result;

}/**

* 字串切分為陣列 (漢字或者乙個字元為單位)

** @param string $str

* @return array

*/private function _cutword( $str )

else

}return $words;

}/**

* 判斷字元是否是ascii字元

** @param string $char

* @return bool

*/private function _isascii( $char )

/*** 判斷字串前3個字元是否是ascii字元

** @param string $str

* @return bool

*/private function _isasciis( $str )

$result = array_count_values( $chars );

if ( empty($result['no']) )

return false;

}/**

* 獲取中文字串的拼音首字元

** @param string $str

* @return string

*/public function getinitials( $str )

$result = array();

if ( $this->_charset == 'utf-8' )

$words = $this->_cutword( $str );

foreach ( $words as $word )

$code = ord( substr($word,0,1) ) * 1000 + ord( substr($word,1,1) );

/*獲取拼音首字母a--z*/

if ( ($i = $this->_search($code)) != -1 )

}return strtoupper(implode('',$result));

}private function _getchar( $ascii )

elseif ( $ascii>=65 && $ascii<=90 )elseif ($ascii>=97 && $ascii<=122)else

}/**

* 查詢需要的漢字內碼(gb2312) 對應的拼音字元( 二分法 )

** @param int $code

* @return int

*/private function _search( $code )

$tmp = (int) round(($lower + $upper) / 2);

if ( !isset($data[$tmp]) )else

if ( $data[$middle] < $code )else if ( $data[$middle] == $code ) else}}

}?>

本文標題: php獲取漢字首字母的函式

本文位址:

oracle 獲取漢字首字母 函式

為了自己使用方便,轉其他寫法 create or replace function func get pinyin capital p name in varchar2 return varchar2 as v compare varchar2 100 v return varchar2 4000 ...

java獲取漢字首字母

public class chinesefcutil 二十六個字母區間對應二十七個端點 gb2312碼漢字區間十進位制表示 private static int table new int 27 對應首字母區間表 private static char initialtable 初始化 static...

python獲取漢字首字母

應用場景之一 可用於獲取名字首字母,在資料庫中查詢記錄時,可以用它來排序輸出。from pytz import unicode 獲取漢字首字母 defmulti get letter str input if isinstance str input,unicode unicode str str ...