php - 截断文本而不截断 HTML

标签 php

这个字符串在 HTML 中有 78 个字符,在没有 HTML 中有 39 个字符:

<p>I really like the <a href="http://google.com">Google</a> search engine.</p>

我想根据非 HTML 字符数截断这个字符串,例如,如果我想将上面的字符串截断为 24 个字符,输出将是:

I really like the <a href="http://google.com">Google</a>

截断在确定要截断的字符数时没有考虑 html,它只考虑了剥离的计数。然而,它并没有留下开放的 HTML 标签。

最佳答案

好吧,这就是我放在一起的,它似乎在工作:

function truncate_html($string, $length, $postfix = '&hellip;', $isHtml = true) {
    $string = trim($string);
    $postfix = (strlen(strip_tags($string)) > $length) ? $postfix : '';
    $i = 0;
    $tags = []; // change to array() if php version < 5.4

    if($isHtml) {
        preg_match_all('/<[^>]+>([^<]*)/', $string, $tagMatches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER);
        foreach($tagMatches as $tagMatch) {
            if ($tagMatch[0][1] - $i >= $length) {
                break;
            }

            $tag = substr(strtok($tagMatch[0][0], " \t\n\r\0\x0B>"), 1);
            if ($tag[0] != '/') {
                $tags[] = $tag;
            }
            elseif (end($tags) == substr($tag, 1)) {
                array_pop($tags);
            }

            $i += $tagMatch[1][1] - $tagMatch[0][1];
        }
    }

    return substr($string, 0, $length = min(strlen($string), $length + $i)) . (count($tags = array_reverse($tags)) ? '</' . implode('></', $tags) . '>' : '') . $postfix;
}

用法:

truncate_html('<p>I really like the <a href="http://google.com">Google</a> search engine.</p>', 24);

该函数是从(做了一个小修改)抓取的:

http://www.dzone.com/snippets/truncate-text-preserving-html

关于php - 截断文本而不截断 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12268387/

相关文章:

php - 在 Laravel 5.7 中限制登录尝试

php - 使用 PHP 生成包含大量行的 JSON

javascript - 文件夹中包含的页面上未调用 .js 文件

php - Number_format PDO 结果

javascript - 使用 CodeIgniter 从 javascript 调用 Controller 方法

php - 控制反转 : Have you ever had to decide what Dependency Injection framework is best for a project? 您选择了哪一个,为什么?

php - 从适用于 PHP 的 AWS 开发工具包提取 protected 请求响应

php - 从多个表中检索内容..可以吗?

php - 从两个表中获取行数并将其放入 PHP 变量中

php - 双空值联合php