导读:以下代码加在项目所在目录的Common目录下的common.php文件里面的,比如作者的就是www Common common.php文件,当然你也可以直接加到thinkph...
以下代码加在项目所在目录的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.com
- 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的字符串,截取字符串长度小于原字符串长度的将什么都不显示,默认是...的,其实后面两个参数是可选的。