查看: 877|回复: 0

[PHP代码] ThinkPHP 模板substr的截取字符串函数

发表于 2017-1-11 12:00:02
游戏辅助AD

ThinkPHP 模板substr的截取字符串函数
在Common/function.php加上以下代码

  1. /**
  2. ** 截取中文字符串
  3. **/
  4. function msubstr($str, $start=0, $length, $charset="utf-8", $suffix=true){
  5. if(function_exists("mb_substr")){
  6. $slice= mb_substr($str, $start, $length, $charset);
  7. }elseif(function_exists('iconv_substr')) {
  8. $slice= iconv_substr($str,$start,$length,$charset);
  9. }else{
  10. $re['utf-8'] = "/[x01-x7f]|[xc2-xdf][x80-xbf]|[xe0-xef][x80-xbf]{2}|[xf0-xff][x80-xbf]{3}/";
  11. $re['gb2312'] = "/[x01-x7f]|[xb0-xf7][xa0-xfe]/";
  12. $re['gbk'] = "/[x01-x7f]|[x81-xfe][x40-xfe]/";
  13. $re['big5'] = "/[x01-x7f]|[x81-xfe]([x40-x7e]|xa1-xfe])/";
  14. preg_match_all($re[$charset], $str, $match);
  15. $slice = join("",array_slice($match[0], $start, $length));
  16. }
  17. $fix='';
  18. if(strlen($slice) < strlen($str)){
  19. $fix='...';
  20. }
  21. return $suffix ? $slice.$fix : $slice;
  22. }
复制代码

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

  1. {$v.title|msubstr=0,5}
复制代码

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

  1. //新闻列表
  2. public function NewsList(){
  3. $this->assign('title','news');
  4. $p = I('page',1);
  5. $listRows = 10;
  6. $News = M('news');
  7. $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();
  8. $this->assign('news',$info);
  9. $count = $News->where(array('type'=>'news','status'=>'1'))->count();
  10. $Page = new Page($count,$listRows);
  11. $show = $Page->show();
  12. $this->assign('page',$show);
  13. //var_dump($info);
  14. $this->display();
  15. }
复制代码



回复

使用道具 举报