How to clip HTML fragments without breaking up tags?

后端 未结 4 1822
谎友^
谎友^ 2021-01-03 12:06

Say I have a 200 character string that contains HTML markup. I want to show a preview of just the first 50 chars. without \'splitting up\' the tags. In other words, the frag

4条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-03 13:06

    Here's a fast and reliable solution using DOMDocument which is part of standard PHP:

    function cut_html ($html, $limit) {
        $dom = new DOMDocument();
        $dom->loadHTML(mb_convert_encoding("
    {$html}
    ", "HTML-ENTITIES", "UTF-8"), LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD); cut_html_recursive($dom->documentElement, $limit); return substr($dom->saveHTML($dom->documentElement), 5, -6); } function cut_html_recursive ($element, $limit) { if($limit > 0) { if($element->nodeType == 3) { $limit -= strlen($element->nodeValue); if($limit < 0) { $element->nodeValue = substr($element->nodeValue, 0, strlen($element->nodeValue) + $limit); } } else { for($i = 0; $i < $element->childNodes->length; $i++) { if($limit > 0) { $limit = cut_html_recursive($element->childNodes->item($i), $limit); } else { $element->removeChild($element->childNodes->item($i)); $i--; } } } } return $limit; }

提交回复
热议问题