Home > Backend Development > PHP Tutorial > Detailed explanation of the interception string function of ThinkPHP template substr

Detailed explanation of the interception string function of ThinkPHP template substr

高洛峰
Release: 2023-03-04 18:04:01
Original
1531 people have browsed it

ThinkPHP template substr interception string function

Add the following code to 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=&#39;...&#39;;
 }
 return $suffix ? $slice.$fix : $slice;
}
Copy after login

When the front-end page needs to intercept the string

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

/*****************************Case************************ *****/

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

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

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

##The above is the entire content of this article, I hope it will be helpful to everyone’s study, I also hope that everyone will support the PHP Chinese website.

For more detailed explanations of the interception string function of ThinkPHP template substr, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template