使用 PHP substr() 和 strip_tags(),同时保留格式且不破坏 HTML

2023-11-29

我有各种 HTML 字符串可以剪切为 100 个字符(被剥离的内容,而不是原始内容),而无需剥离标签,也不会破坏 HTML。

原始 HTML 字符串(288 个字符):

$content = "<div>With a <span class='spanClass'>span over here</span> and a
<div class='divClass'>nested div over <div class='nestedDivClass'>there</div>
</div> and a lot of other nested <strong><em>texts</em> and tags in the air
<span>everywhere</span>, it's a HTML taggy kind of day.</strong></div>";

标准装饰:修剪至 100 个字符并进行 HTML 中断,剥离的内容约为 40 个字符:

$content = substr($content, 0, 100)."..."; /* output:
<div>With a <span class='spanClass'>span over here</span> and a
<div class='divClass'>nested div ove... */

剥离的 HTML:输出正确的字符数,但明显丢失格式:

$content = substr(strip_tags($content)), 0, 100)."..."; /* output:
With a span over here and a nested div over there and a lot of other nested
texts and tags in the ai... */

部分解决方案:使用 HTML Tidy 或 purifier 关闭标签会输出干净的 HTML,但有 100 个字符的 HTML 未显示内容。

$content = substr($content, 0, 100)."...";
$tidy = new tidy; $tidy->parseString($content); $tidy->cleanRepair(); /* output:
<div>With a <span class='spanClass'>span over here</span> and a
<div class='divClass'>nested div ove</div></div>... */

挑战:输出干净的 HTML 和n字符数(不包括 HTML 元素的字符数):

$content = cutHTML($content, 100); /* output:
<div>With a <span class='spanClass'>span over here</span> and a
<div class='divClass'>nested div over <div class='nestedDivClass'>there</div>
</div> and a lot of other nested <strong><em>texts</em> and tags in the
ai</strong></div>...";

类似的问题

  • 如何在不破坏标签的情况下剪辑 HTML 片段
  • 剪切 HTML 字符串而不破坏 HTML 标签

不神奇,但有效。

function html_cut($text, $max_length)
{
    $tags   = array();
    $result = "";

    $is_open   = false;
    $grab_open = false;
    $is_close  = false;
    $in_double_quotes = false;
    $in_single_quotes = false;
    $tag = "";

    $i = 0;
    $stripped = 0;

    $stripped_text = strip_tags($text);

    while ($i < strlen($text) && $stripped < strlen($stripped_text) && $stripped < $max_length)
    {
        $symbol  = $text{$i};
        $result .= $symbol;

        switch ($symbol)
        {
           case '<':
                $is_open   = true;
                $grab_open = true;
                break;

           case '"':
               if ($in_double_quotes)
                   $in_double_quotes = false;
               else
                   $in_double_quotes = true;

            break;

            case "'":
              if ($in_single_quotes)
                  $in_single_quotes = false;
              else
                  $in_single_quotes = true;

            break;

            case '/':
                if ($is_open && !$in_double_quotes && !$in_single_quotes)
                {
                    $is_close  = true;
                    $is_open   = false;
                    $grab_open = false;
                }

                break;

            case ' ':
                if ($is_open)
                    $grab_open = false;
                else
                    $stripped++;

                break;

            case '>':
                if ($is_open)
                {
                    $is_open   = false;
                    $grab_open = false;
                    array_push($tags, $tag);
                    $tag = "";
                }
                else if ($is_close)
                {
                    $is_close = false;
                    array_pop($tags);
                    $tag = "";
                }

                break;

            default:
                if ($grab_open || $is_close)
                    $tag .= $symbol;

                if (!$is_open && !$is_close)
                    $stripped++;
        }

        $i++;
    }

    while ($tags)
        $result .= "</".array_pop($tags).">";

    return $result;
}

使用示例:

$content = html_cut($content, 100);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 PHP substr() 和 strip_tags(),同时保留格式且不破坏 HTML 的相关文章

  • CTYPE_ALNUM 的奇怪之处

    我的 PHP 函数 CTYPE ALNUM 有一个奇怪的问题 if i do PHP words if ctype alnum words Echo Don t work else Echo Work 这将回显 工作 但是如果我有一个表格
  • 如何解析这个 OFX 文件?

    这是原始 ofx 文件 因为它来自 m 银行 不用担心 没有什么敏感信息 我剪掉了所有交易的中间部分 开放金融交易所 OFX 是一个 用于交换的数据流格式 演变的财务信息 来自微软的开放金融 连接 OFC 和 Intuit 的 Open 交
  • 查找最近的城市,例如 oodle.com

    因此 我正在尝试开发一个显示用户列表的应用程序 该网站应该检测用户位置 我为此使用 maxmind api 然后显示用户位置 用户指定半径内的城市的列表 我该怎么做呢 MaxMind API 让我可以通过 IP 地址检测用户的城市 但如何找
  • Bootstrap 3 无法在 Symfony3 中工作

    我刚刚开始学习 Symfony 3 我正在尝试使用 bootstrap 3 为我的表单设置主题 根据文档 http symfony com doc current cookbook form form customization html
  • 准备好的语句与存储过程

    如果您使用 php5 和 mysql5 使用存储过程比准备语句有实质性优势吗 我在某处读到 您可能无法从 mysql5 存储过程中获得实质性的性能提升 它们实际上并不是同一件事 对于存储过程 您的数据库逻辑驻留在数据库内部 如果多次调用准备
  • 使用 Bootstrap 粘性导航栏进行 Href 跳转 [重复]

    这个问题在这里已经有答案了 因此 我有一个带有下拉菜单的粘性导航栏 可以让我跳转到页面的不同部分 但是 当我跳转到不同的部分时 导航栏会覆盖我跳转到的 div 的开头 我检查了导航栏 它的高度为 58 带有填充和所有内容 如何将跳转偏移 5
  • 如何使用php取消设置mongodb中的所有记录字符串?

    我的数据库记录了这样的事情 id ObjectId 50118b145e69ef2c0e007a2 class customer dbid 1829 value email protected cdn cgi l email protect
  • PHP - 搜索字符串中的特定单词数组并与可选的 + 或 - 匹配

    我需要在字符串中搜索特定单词并将匹配结果作为变量 我在数组中有一个特定的单词列表 names array Blue Gold White Purple Green Teal Purple Red drag Glowing looks to
  • 在 Kohana 3.2 视图中输出图像

    我有以下脚本将图像输出到浏览器 效果很好 file to output SERVER DOCUMENT ROOT static imgs uploads 20110318172207 16 jpg header Content Type i
  • 使用 PHP SDK 在亚马逊 S3 上上传文件

    我正在尝试通过 PHP SDK 在我的亚马逊 S3 存储桶上上传文件 但是我的脚本不起作用 我有一个空白页面 没有任何错误或异常消息 编辑 在 php ini 中启用 display error 后 我有下面的错误消息 看起来 sdk 在我
  • 仅使用视频标签实时流式传输到 HTML5(不带 webrtc)

    我想将实时编码数据包装到 webm 或 ogv 并将其发送到 html5 浏览器 webm 或 ogv 可以做到这一点吗 Mp4 由于其 MDAT 原子而无法做到这一点 无法实时将h264和mp3打包并发送给客户端 假设我正在从网络摄像头输
  • HTML5 下载属性不适用于 Mozilla [重复]

    这个问题在这里已经有答案了 a class download btn href https example com test pdf target blank Download a 我上面有简单的下载链接html5代码 它在 mozilla
  • 设置快捷方式以替换 VIM 中轻松选择的字符串

    我有很多 php html 文件 其中包含许多应该使用 gettext 国际化的字符串 因此 我必须遍历每个文件 找到 消息 字符串并将每个字符串替换为 I use vim and would like to setup a shortcu
  • 删除 PHP 中的标头

    为了允许缓存 PHP 生成的文件 我想确保 Pragma no cache 标头是not放 但是 如何删除可能已经设置的标头 这就对了could有可能 有人在代码中的某个地方写了header Pragma no cache 现在我想确保标头
  • 滚动到 HTML 网站中的顶部 JavaScript

    我正在尝试在我的网站中实现滚动到顶部功能 www arrow tvseries com 网站上可以看到 按钮 但它无法正常工作 因为单击时它不会滚动到页面顶部 更重要的是 我希望 滚动到顶部按钮 在向下滚动 例如一半页面 时可见 这是 Ja
  • php 中

    的新行

    我目前在数据库中有很多笑话 这些笑话都是用 nl2br 格式化的 它会产生 This is just dummy text Lorem ipsum dolor sit amet consectetur adipiscing elit br
  • 可以用html渲染图像吗?

    我可以控制从文本文件获取 html 并在网页中呈现该 html 的页面 现在它必须在某处添加图像并引用该图像 src 我想知道我们是否可以与其他 html 代码一起渲染图像 这可能吗 是的 你需要一个数据 URI 方案 http en wi
  • jquery ajax - 返回 json 或纯 html 更好

    当时间从ajax返回时 我应该返回 json 编码 并使用 jquery parseJSON 并使用 document createElement 并将数据附加到刚刚创建的元素内 或者最好以 html 文本形式返回 example div
  • 使用 wp_read_audio_metadata()

    我正在尝试从 WordPress 中的 mp3 文件获取一些元数据 特别是长度变量 这是我的一些代码 这里没有显示 但我已经包含了 wp admin includes media php 文件 当我查看我的页面时http beta open
  • 背景过滤器不适用于 Chrome 中的嵌套元素

    我有一个div outer和里面一个div inner 都与position absolute and backdrop filter blur 8px https jsbin com nihakiqocu 1 edit html css

随机推荐