PHP下获取字符串中的汉字

版权声明:默先森||[email protected] https://blog.csdn.net/Error_Q/article/details/90175478

吾生也有涯,而知也无涯~欢迎优化补充、指正!

(直接调用方法稍加修改即可使用,或者单独粘贴使用相应片段!)

*本文是在tp5下进行编译与调试的

代码如下,使用时直接调用本方法($length 设置获取汉字的长度)

获取字符串中的汉字需要使用到 mb_substr()函数(详情见文章尾部)

    //获取$str里的前几个汉字
    public function gainChinese($str='',$length='2')
    {
        $count = 0;//
        $str_count = strlen($str);//字符个数
        $result = '';
        if ($str_count>0) {
            for($i=0;$i<$str_count;$i++){
                $str_i = mb_substr($str,$i,1,'utf-8');//获取字符串中的第$i个字符
                if(preg_match('/^[\x{4e00}-\x{9fa5}]+$/u',$str_i) && $count<$length){
                    $result .= $str_i;
                    $count ++;
                }
            }
        }
        return $result;
    }

mb_substr()介绍如下: 

https://www.php.net/manual/zh/function.mb-substr.php学习本函数! 

猜你喜欢

转载自blog.csdn.net/Error_Q/article/details/90175478
今日推荐