PHP群:95885625 Hbuilder+MUI群:81989597 站长QQ:634381967
    您现在的位置: 首页 > 开发编程 > ThinkPhp教程 > 正文

    thinkphp中如何截取中文字符串???

    作者:admin来源:网络浏览:时间:2020-09-30 00:07:50我要评论
    导读:以下代码加在项目所在目录的Common目录下的common.php文件里面的,比如作者的就是www Common common.php文件,当然你也可以直接加到thinkph...
    以下代码加在项目所在目录的Common目录下的common.php文件里面的,比如作者的就是www/Common/common.php文件,当然你也可以直接加到thinkphp的Common/common.php文件里面,这样就所有的项目都可以使用了。

     
    复制代码代码如下:
    1. function truncate_cn($string,$length=0,$ellipsis='…',$start=0){
    2.     $string=strip_tags($string);
    3.     $string=preg_replace('/\n/is','',$string);
    4.     //$string=preg_replace('/ | /is','',$string);//清除字符串中的空格
    5.     $string=preg_replace('/ /is','',$string);
    6.     preg_match_all("/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/",$string,$string);
    7.     if(is_array($string)&&!empty($string[0])){
    8.         $string=implode('',$string[0]);
    9.         if(strlen($string)<$start+1){
    10.             return '';
    11.         }
    12.         preg_match_all("/./su",$string,$ar);
    13.         $string2='';
    14.         $tstr='';
    15.         //www.phpernote.com
    16.         for($i=0;isset($ar[0][$i]);$i++){
    17.             if(strlen($tstr)<$start){
    18.                 $tstr.=$ar[0][$i];
    19.             }else{
    20.                 if(strlen($string2)<$length+strlen($ar[0][$i])){
    21.                     $string2.=$ar[0][$i];
    22.                 }else{
    23.                     break;
    24.                 }
    25.             }
    26.         }
    27.         return $string==$string2?$string2:$string2.$ellipsis;
    28.     }else{
    29.         $string='';
    30.     }
    31.     return $string;
    32. }

    在thinkphp的模板中用法如下:

    {$info.subject|truncate_cn=40,'',0}
    
    意思是截取$info['subject']字符串,从第0个字符串开始截取长度为40的字符串,截取字符串长度小于原字符串长度的将什么都不显示,默认是...的,其实后面两个参数是可选的。
    转载请注明(B5教程网)原文链接:https://b5.mxunkeji.com/content-83-271-1.html
    相关热词搜索: thinkphp 截取 字符串
    上一篇:第一页