在PHP中獲取漢字的首字母可以通過以下方法實現(xiàn):
function getFirstChar($str){
$firstChar = '';
$s = iconv("UTF-8", "gb2312", $str);
if (preg_match("/^([A-Za-z])/", $str)) { //如果是英文字母直接返回
return strtoupper($str[0]);
}
if (ord($str) > 128) { //漢字
$asc = ord($s{0}) * 256 + ord($s{1}) - 65536;
if ($asc >= -20319 and $asc <= -20284) {
$firstChar = 'A';
}
if ($asc >= -20283 and $asc <= -19776) {
$firstChar = 'B';
}
if ($asc >= -19775 and $asc <= -19219) {
$firstChar = 'C';
}
if ($asc >= -19218 and $asc <= -18711) {
$firstChar = 'D';
}
if ($asc >= -18710 and $asc <= -18527) {
$firstChar = 'E';
}
if ($asc >= -18526 and $asc <= -18240) {
$firstChar = 'F';
}
if ($asc >= -18239 and $asc <= -17923) {
$firstChar = 'G';
}
if ($asc >= -17922 and $asc <= -17418) {
$firstChar = 'H';
}
if ($asc >= -17417 and $asc <= -16475) {
$firstChar = 'J';
}
if ($asc >= -16474 and $asc <= -16213) {
$firstChar = 'K';
}
if ($asc >= -16212 and $asc <= -15641) {
$firstChar = 'L';
}
if ($asc >= -15640 and $asc <= -15166) {
$firstChar = 'M';
}
if ($asc >= -15165 and $asc <= -14923) {
$firstChar = 'N';
}
if ($asc >= -14922 and $asc <= -14915) {
$firstChar = 'O';
}
if ($asc >= -14914 and $asc <= -14631) {
$firstChar = 'P';
}
if ($asc >= -14630 and $asc <= -14150) {
$firstChar = 'Q';
}
if ($asc >= -14149 and $asc <= -14091) {
$firstChar = 'R';
}
if ($asc >= -14090 and $asc <= -13319) {
$firstChar = 'S';
}
if ($asc >= -13318 and $asc <= -12839) {
$firstChar = 'T';
}
if ($asc >= -12838 and $asc <= -12557) {
$firstChar = 'W';
}
if ($asc >= -12556 and $asc <= -11848) {
$firstChar = 'X';
}
if ($asc >= -11847 and $asc <= -11056) {
$firstChar = 'Y';
}
if ($asc >= -11055 and $asc <= -10247) {
$firstChar = 'Z';
}
} else {
$firstChar = strtoupper($str[0]);
}
return $firstChar;
}
$str = '你好世界';
echo getFirstChar($str); //輸出 N
以上代碼可以根據(jù)漢字的unicode碼來判斷首字母,返回結(jié)果為漢字拼音首字母的大寫字母。