php如何获取汉字首字母

   2024-10-01 9790
核心提示:在PHP中获取汉字的首字母可以通过以下方法实现:function getFirstChar($str){$firstChar = '';$s = iconv(

在PHP中获取汉字的首字母可以通过以下方法实现:

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

以上代码可以根据汉字的unicode码来判断首字母,返回结果为汉字拼音首字母的大写字母。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式 | 网站留言    |  赣ICP备2021007278号