首页
技术
生活
常用脚本
技术文档
关于
文章截取摘要,去掉dom标签
  • 作者:王树东
  • 发布于:2020-09-27 17:12:35
  • 更新于:2020-09-27 17:12:35
<?php
namespace app\service;

class ArticleService
{
    //截取摘要
    public function cutChar($document)
    {
        $document = trim($document);
        if (strlen($document) <= 0) {
            return $document;
        }
        $search = array("'<script[^>]*?>.*?</script>'si", // 去掉 javascript
            "'<[\/\!]*?[^<>]*?>'si", // 去掉 HTML 标记
            "'([\r\n])[\s]+'", // 去掉空白字符
            "'/\s(?=\s)/'",
            "'/[nrt]/'",
            "'/[\n\r\t]/'",
            "'/s(?=s)/'",
            "'&(quot|#34);'i", // 替换 HTML 实体
            "'&(amp|#38);'i",
            "'&(lt|#60);'i",
            "'&(gt|#62);'i",
            "'&(nbsp|#160);'i",
        );
        $replace = array("", "", "\\1", "\"", "&", "<", ">", " ");
        $String = @preg_replace($search, $replace, $document);
        return $this->sysSubStr($String, 200, true);
    }

    public function sysSubStr($String, $Length, $Append = false)
    {
        if (strlen($String) <= $Length) {
            return $String;
        } else {
            $I = 0;
            while ($I < $Length) {
                $StringTMP = substr($String, $I, 1);
                if (ord($StringTMP) >= 224) {
                    $StringTMP = substr($String, $I, 3);
                    $I = $I + 3;
                } elseif (ord($StringTMP) >= 192) {
                    $StringTMP = substr($String, $I, 2);
                    $I = $I + 2;
                } else {
                    $I = $I + 1;
                }
                $StringLast[] = $StringTMP;
            }
            $StringLast = implode("", $StringLast);
            if ($Append) {
                $StringLast .= "...";
            }
            return $StringLast;
        }
    }
}

评论

暂无评论

发表评论

王树东的博客

Copyright © 2014-2020冀ICP备12011960号-15

FLOW ME

wsd312@163.com技术咨询和服务
starkland@163.combusiness cooperation

公众号

个人微信交个朋友
欢迎关注服务号更多技术等你来看