How to clip HTML fragments without breaking up tags?

后端 未结 4 1818
谎友^
谎友^ 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条回答
  •  猫巷女王i
    2021-01-03 12:46

    Short answer: convert it to DOM with DOMDocument::loadHTML($string) then walk the tree counting the characters in the text nodes. When you hit your limit, replace the rest of that node with '...' or the empty string, and simply call $node->parentNode->removeChild($node) on all subsequent nodes.

提交回复
热议问题