4

该字符串包含 78 个字符(含 HTML)和 39 个字符(不含 HTML):

<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 标签。

4

1 回答 1

9

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

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

于 2012-09-07T01:06:53.440 回答