Last active
April 11, 2020 18:15
-
-
Save Mykola-Veryha/e08dcb109543710e070aefd3cb26564b to your computer and use it in GitHub Desktop.
Truncate html
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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