首页 > 解决方案 > 使用 substr 获取前 x 个字符时如何跳过 HTML 标记

问题描述

在一些博客文件中,我在 500 个字符后使用“阅读更多”按钮。要从字符串(即 blogmessage)中获取前 500 个字符,我使用substr如下:

$blog_message_reduced = substr($blog_message, 0, 500);

字符串$blog_message如下所示:

lorem ipsum is simply dummy text of the printing and typesetting industry <img src="data/uploads/image.jpg" class="img-responsive" style="width: 100%" /> and some more text behind the image.... 

有时,当我写博客文章时,500 个字符的限制正好在img 标签内。

$blog_message_reduced然后 HTML 输出类似于:

lorem ipsum is simply dummy text of the <img src="data/uplo

在上面的示例中,单词uploads的o已达到500 。

因此,我正在寻找一种方法来在使用 500 进行裁剪时忽略img标签。substr(当达到 500 时,切勿剪切img标签;在这种情况下,请在img标签后立即剪切)。

我怎样才能做到这一点?

标签: phpsubstr

解决方案


在裁剪之前使用 PHP 的strip_tags()

<?php

$str = 'lorem ipsum is simply dummy text of the printing and typesetting industry <img src="data/uploads/image.jpg" class="img-responsive" style="width: 100%" /> and some more text behind the image.... ';
$pre = strip_tags($str);
$crop = substr($pre, 0, 100);
echo $crop;

// Output:
// lorem ipsum is simply dummy text of the printing and typesetting industry and some more text behind

或与一些更高级的用法相同

<?php

$str = 'lorem ipsum is simply dummy text of the printing and typesetting industry <img src="data/uploads/image.jpg" class="img-responsive" style="width: 100%" /> and some more text behind the image.... ';
echo crop($str, 100, '... (read more)', true, true);

function crop($content, $maxCharacters, $append = '...', $respectWordBoundaries = false, $stripTags = false)
{
    if ($stripTags) {
        $content = strip_tags($content);
    }

    if ($maxCharacters) {
        if (mb_strlen($content, 'utf-8') > abs($maxCharacters)) {
            $truncatePosition = false;
            if ($maxCharacters < 0) {
                $content = mb_substr($content, $maxCharacters, null, 'utf-8');
                if ($respectWordBoundaries) {
                    $truncatePosition = strpos($content, ' ');
                }
                $content = $truncatePosition ? $append . substr($content, $truncatePosition) : $append . $content;
            } else {
                $content = mb_substr($content, 0, $maxCharacters, 'utf-8');
                if ($respectWordBoundaries) {
                    $truncatePosition = strrpos($content, ' ');
                }
                $content = $truncatePosition ? substr($content, 0, $truncatePosition) . $append : $content . $append;
            }
        }
    }
    return $content;
}

推荐阅读