以下代碼加在項目所在目錄的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的字串,截取字串長度小於原字串長度的將什麼都不顯示,預設是...的,其實後面兩個參數是可選的。