Skip to content

Instantly share code, notes, and snippets.

@Mykola-Veryha
Last active April 11, 2020 18:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Mykola-Veryha/e08dcb109543710e070aefd3cb26564b to your computer and use it in GitHub Desktop.
Save Mykola-Veryha/e08dcb109543710e070aefd3cb26564b to your computer and use it in GitHub Desktop.
Truncate html
<?php
function htmlTruncate(string $html, int $max_lenght) {
$dom= new \DOMDocument();
$dom->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));
$xpath = new \DOMXPath($dom);
$body = $xpath->query('/html/body')->item(0);
$prev_lenght = 0;
$removed_children = [];
foreach ($body->childNodes as $child_node) {
if ($prev_lenght > $max_lenght) {
$removed_children[] = $child_node;
}
else {
$child_lenght = mb_strlen($child_node->textContent);
$current_lenght = $prev_lenght + $child_lenght;
if ($current_lenght > $max_lenght) {
$child_node->nodeValue = mb_substr($child_node->nodeValue, 0, $max_lenght - $prev_lenght);
}
$prev_lenght = $current_lenght;
}
}
foreach ($removed_children as $removed_child) {
$body->removeChild($removed_child);
}
return $dom->saveHTML($body);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment