3v4l.org

run code in 150+ php & hhvm versions
Bugs & Features
<?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);
Output for 5.4.0 - 5.4.15
Parse error: syntax error, unexpected ''<p>I can haz <strong> html tr' (T_ENCAPSED_AND_WHITESPACE), expecting ')' in /in/8tBjl on line 63
Process exited with code 255.
Output for 5.3.0 - 5.3.25
Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting ')' in /in/8tBjl on line 63
Process exited with code 255.