程序员人生 网站导航

smarty输出截取字符的扩展cn_truncate函数介绍

栏目:php教程时间:2014-08-27 10:48:51
今天给大家介绍一个函数,smarty输出截取字符的扩展cn_truncate函数,函数所在位置一般是在目录library\smarty\plugins\modifier_cn_truncate.php文件中
原函数代码如下:
  1. function smarty_modifier_cn_truncate($string$length = 80, $etc = '...'$count_words = true,$w_tags=false)  
  2. {   if($w_tags==true){  
  3.         $string=strip_tags($string);  
  4.     }  
  5.     $wordscut = '';  
  6.     mb_internal_encoding("UTF-8");  
  7.     if ($length == 0)return '';  
  8.     if ( strlen$string ) <= $length ) return $string;  
  9.     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$info);   
  10.     if$count_words ){  
  11.         $j = 0;  
  12.         for($i=0; $i<count($info[0]); $i++) {  
  13.             $wordscut .= $info[0][$i];  
  14.             if( ord( $info[0][$i] ) >=128 ){  
  15.                 $j = $j+2;  
  16.             }else{  
  17.                 $j = $j + 1;  
  18.             }  
  19.             if ($j >= $length ) {  
  20.                 return $wordscut.$etc;  
  21.             }  
  22.         }  
  23.         return join(''$info[0]);  
  24.     }  
  25.     return join("",array_slice$info[0],0,$length ) ).$etc;  
  26.  

cn_truncate函数目的:
1、在模板中直接截取中文字符
2、可保留原来的字符串style,如 font 等
用法:
cn_truncate 用法大致同官方的 truncate 函数,如下:
{$item.title|cn_truncate:18:"...":true}

第1个参数 18 表示截取 18 个汉字
第2个参数 ... 表示,如果多余18个汉字,则显示 ...
第3个参数 true 表示保留文字的初始颜色。 false 表示去掉颜色。
应用实例:可以在首页调用公司介绍等等

这个函数唯一不好的就是他不能去掉html标签,有时候是需要截取新闻前面一句话的,不包括里面的html,这个该怎么操作呢,只需要把函数改变下就行了
 

  1. function smarty_modifier_cn_truncate($string$length = 80, $etc = '...'$count_words = true,$w_tags=false)  
  2. {   if($w_tags==true){  
  3.         $string=strip_tags($string);  
  4.     } 

把函数上面改成这样就可以了,调用的时候取$w_tags=true即可。例如{$item.title|cn_truncate:18:"...":true:true},好了,还有什么不明白的可以到程序员人生网站留言,谢谢大家

------分隔线----------------------------
------分隔线----------------------------

最新技术推荐