ThinkPHP 3.1.3貌似沒有內建的截取中文字串的方法,找了半天沒找到,下面作者自己加了一個截取中文字串的函數,具體代碼如下,有需要的朋友可以參考下。
以下代碼加在項目所在目錄的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.phpernote.comfor($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的字串,截取字串長度小於原字串長度的將什麼都不顯示,預設是...的,其實後面兩個參數是可選的。
您可能感興趣的文章
- javascript實現截取字串功能總結(包括使用Js截取中文字元的介紹)
- thinkphp模板中判斷volist迴圈的最後一條記錄
- php效能最佳化:使用 isset()判斷字串長度速度比strlen()更快
- js限制只能輸入英文字母和數字,不能輸入中文和其他特殊字元的辦法
- thinkphp自動驗證與自動填滿無效的解決辦法
- php提取字串中的數字
- 如何去除codeIgniter開發的網站url裡面的index.php字串
- php判斷字串是否全英文,純中文,中英文組合的方法
http://www.bkjia.com/PHPjc/764109.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/764109.htmlTechArticleThinkPHP 3.1.3貌似沒有內建的截取中文字串的方法,找了半天沒找到,下面作者自己加了一個截取中文字串的函數,具體代碼如下,有需...