3v4l.org

run code in 300+ PHP versions simultaneously
<?php class Html{ protected $reachedLimit = false, $totalLen = 0, $maxLen = 25; public static function trim($html, $maxLen = 25){ $dom = new DomDocument(); $dom->loadHTML($html); $html = new static(); $html->walk($dom, $maxLen); // remove wrapper tags added by DD (doctype, html...) // http://stackoverflow.com/a/6953808/1058140 $dom->removeChild($dom->firstChild); $dom->replaceChild($dom->firstChild->firstChild->firstChild, $dom->firstChild); return $dom->saveHTML(); } protected function walk(DomNode $node, $maxLen){ // remove any nodes that passed our limit if($this->reachedLimit){ $node->parentNode->removeChild($node); return; } // only text nodes should have text, // so do the splitting here if($node instanceof DomText){ $this->totalLen += $nodeLen = strlen($node->nodeValue); if($this->totalLen > $maxLen){ $node->nodeValue = substr($node->nodeValue, 0, $nodeLen - ($this->totalLen - $maxLen)); $this->reachedLimit = true; } } if(!$node->hasChildNodes()) return; // if node has children, walk its child elements foreach($node->childNodes as $child) $this->walk($child, $maxLen); } } print html::trim('<p>I can haz <strong> html trim </strong>', 14);

preferences:
30.7 ms | 402 KiB | 5 Q