🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
新浪等一些大平台新闻网站经常使用内容分页技术,把一篇文章分成若干部分,每一部分作为其中一页,以这种形式展现给用户,不仅提升了用户体验,也提高了网站加载内容的效率,但是这种做法最大的问题就是在截取字符串的时候会出现乱码,下面是我做的一个测试,基本没什么问题,没有乱码出现。 代码如下: header('content-type:text/html;charset="utf-8"'); class StrPage{ private $file;//文件内容 private $current;//当前页 private $pageLen;//每页显示的内容长度 private $totalPage;//总页数 private $url;//url地址 public function __construct($file,$len){ $a = array(' ',' ','\t','\n','\r','\s'); $b = array('','','','',''); $this->file = str_replace($a,$b,file_get_contents($file)); $this->current = $_GET['page'] ? $_GET['page'] : 1; $this->pageLen = $len; $this->totalPage = $this->getTotalPage(); $this->url = $this->getUrl(); } private function getTotalPage(){ return ceil( strlen($this->file) / $this->pageLen ); } private function getUrl(){ $url = parse_url($_SERVER['REQUEST_URI']); parse_str($url['query'],$arry); unset($arry['page']); $query = http_build_query($arry); return $url['path'].'?'.$query.'&page='; } private function first(){ if($this->current>1){ return '<a href="'.$this->url.'1">首页&nbsp;&nbsp;</a>'; } } private function next(){ if($this->current<$this->totalPage){ return '<a href="'.$this->url.($this->current+1).'">下一页&nbsp;&nbsp;</a>'; } } private function pre(){ if($this->current>1){ return '<a href="'.$this->url.($this->current-1).'">上一页&nbsp;&nbsp;</a>'; } } private function end(){ return '<a href="'.$this->url.$this->totalPage.'">末页</a>'; } private function subStrs($str){ if(ord(substr($this->file,$str,1))>127){ if(strlen(substr($this->file,0,$str))%3==1){ return $str+=2; }else if(strlen(substr($this->file,0,$str))%3==2){ return $str+=1; }else{ return $str+=0; } }else{ return $str+=0; } } public function getContents(){ $prePageLen = $this->subStrs(($this->current-1)*$this->pageLen); $currentPageLen = $this->subStrs($this->current*$this->pageLen); $string = substr($this->file,$prePageLen,$currentPageLen-$prePageLen); echo $prePageLen; echo $currentPageLen; return $string; } public function pageStyle(){ return '共有'.$this->totalPage.'页&nbsp;&nbsp;'.$this->first().$this->pre().$this->next().$this->end(); } } $php = new StrPage('file.txt',500); echo '<div style="width:558px;height:368px;border:1px solid #f00;line-height:14px;font-size:14px">'.$php->getContents().'</div>'; echo '<div>'; echo $php->pageStyle(); echo '</div>'; 注意,你的文件编码和php脚本的编码要一致,我这边用的是utf8编码,在截取字符串避免乱码的时候与gbk稍有不同,详情请看上一章节。