ThinkPHP 模板substr的截取字符串函数详解

yipeiwu_com5年前PHP代码库

ThinkPHP 模板substr的截取字符串函数

在Common/function.php加上以下代码

/**
** 截取中文字符串
**/
function msubstr($str, $start=0, $length, $charset="utf-8", $suffix=true){
 if(function_exists("mb_substr")){
 $slice= mb_substr($str, $start, $length, $charset);
 }elseif(function_exists('iconv_substr')) {
 $slice= iconv_substr($str,$start,$length,$charset);
 }else{
 $re['utf-8'] = "/[x01-x7f]|[xc2-xdf][x80-xbf]|[xe0-xef][x80-xbf]{2}|[xf0-xff][x80-xbf]{3}/";
 $re['gb2312'] = "/[x01-x7f]|[xb0-xf7][xa0-xfe]/";
 $re['gbk'] = "/[x01-x7f]|[x81-xfe][x40-xfe]/";
 $re['big5'] = "/[x01-x7f]|[x81-xfe]([x40-x7e]|xa1-xfe])/";
 preg_match_all($re[$charset], $str, $match);
 $slice = join("",array_slice($match[0], $start, $length));
 } 
 $fix='';
 if(strlen($slice) < strlen($str)){
  $fix='...';
 }
 return $suffix ? $slice.$fix : $slice;
}

前端页面需要截取字符串时

{$v.title|msubstr=0,5}

/****************************案例****************************/

//新闻列表
 public function NewsList(){
 $this->assign('title','news');
 $p = I('page',1);
 $listRows = 10;
 $News = M('news');
 $info = $News->field('id,title,subtitle,publish_date,img,content')->where(array('type'=>'news','status'=>'1'))->order('flag desc,sort_no desc')->page($p,$listRows)->select();
 $this->assign('news',$info);
 $count = $News->where(array('type'=>'news','status'=>'1'))->count();
 $Page = new Page($count,$listRows);
 $show = $Page->show();
 $this->assign('page',$show);
 //var_dump($info);
 $this->display();
 }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【宜配屋www.yipeiwu.com】。

相关文章

2010年最新PHP类的精髓归纳第1/2页

 一:结构和调用(实例化):class className{} ,调用:$obj = new className();当类有构造函数时,还应传入参数。如$obj = new c...

php获取微信基础接口凭证Access_token

本文为大家分享了php获取微信基础接口凭证Access_token的具体代码,供大家参考,具体内容如下 access_token是公众号的全局唯一票据,公众号调用各接口时都需使用acce...

IIS下PHP的三种配置方式对比

 在Windows IIS 6.0下配置PHP,通常有CGI、ISAPI和FastCGI三种配置方式,这三种模式都可以在IIS 6.0下成功运行,下面我就讲一下这三种方式配置的区别和性能...

用PHP代替JS玩转DOM的思路及示例代码

事情的起源比较简单,我需要把一个导航页的数据整理好写入数据库。一个比较直观的方法是对html文件进行分析,通用的方法是用php的正则表达式来匹配。但是这样做开发和维护都很困难,代码可读性...

php中ltrim()、rtrim()与trim()删除字符空格实例

本文实例讲述了php中ltrim()、rtrim()与trim()删除字符空格的方法。分享给大家供大家参考。具体分析如下: php中的trim函数不能像asp中的一样,可以自动删除所有空...