thinkphp截取中文字串的程式碼

來源:互聯網
上載者:User

以下代碼加在項目所在目錄的Common目錄下的common.php檔案裡面的,比如作者的就是www/Common/common.php檔案,當然你也可以直接加到thinkphp的Common/common.php檔案裡面,這樣就所有的項目都可以使用了。

 代碼如下 複製代碼

function truncate_cn($string,$length=0,$ellipsis='…',$start=0){
 $string=strip_tags($string);
 $string=preg_replace('/\n/is','',$string);
 //$string=preg_replace('/ | /is','',$string);//清除字串中的空格
 $string=preg_replace('/ /is','',$string);
 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);
 if(is_array($string)&&!empty($string[0])){
  $string=implode('',$string[0]);
  if(strlen($string)<$start+1){
   return '';
  }
  preg_match_all("/./su",$string,$ar);
  $string2='';
  $tstr='';
  //www.111cn.net
  for($i=0;isset($ar[0][$i]);$i++){
   if(strlen($tstr)<$start){
    $tstr.=$ar[0][$i];
   }else{
    if(strlen($string2)<$length+strlen($ar[0][$i])){
     $string2.=$ar[0][$i];
    }else{
     break;
    }
   }
  }
  return $string==$string2?$string2:$string2.$ellipsis;
 }else{
  $string='';
 }
 return $string;
}

在thinkphp的模板中用法如下:

 代碼如下 複製代碼

{$info.subject|truncate_cn=40,'',0}

意思是截取$info['subject']字串,從第0個字串開始截取長度為40的字串,截取字串長度小於原字串長度的將什麼都不顯示,預設是...的,其實後面兩個參數是可選的。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.