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

yipeiwu_com4年前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】。

相关文章

PHP获取路径和目录的方法总结【必看篇】

PHP获取路径和目录的方法总结【必看篇】

PHP获取目录和的方法通过魔术变量;通过超级全局变量;通过相关函数等等: <?php /** * PHP获取路径或目录实现 */ //魔术变量,获取当前文件...

安装apache2.2.22配置php5.4(具体操作步骤)

修改 apache2.2/httpd.conf 配置文件,让apache能够解析php文件 #修改监听端口Listen 8011 #在LoadModule的最后一段后面添加下面一句话Lo...

PHP内置加密函数详解

Md5()加密算法 方式: 单向加密 语法: md5(string $str [, bool $raw_output = false]) $str:原始字符串 $raw_output:如...

PHP关于foreach复制知识点总结

PHP的foreach是一个非常整洁和切中要害的语言结构。仍然有些人不喜欢使用它,因为他们认为它是缓慢的。一个通常命名的原因是foreach复制它迭代的数组。 因此,一些人建议写:...

php+xml实现在线英文词典之添加词条的方法

本文实例讲述了php+xml实现在线英文词典之添加词条的方法。分享给大家供大家参考。具体如下: 接着上一篇《php+xml实现在线英文词典查询的方法》,这里要添加一个功能,提交英文单词和...