Skip to content

Instantly share code, notes, and snippets.

Created May 13, 2016 23:09
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 anonymous/9a6523ae39cf44ca717ee945d96709f0 to your computer and use it in GitHub Desktop.
Save anonymous/9a6523ae39cf44ca717ee945d96709f0 to your computer and use it in GitHub Desktop.
Truncate HTML
function truncate_html($text, $length = 30, $truncate_string = '...', $truncate_lastspace = false)
{
// Don't truncate if visible (non-HTML) text length's already less than or equal to target length
if (strlen(strip_tags($text)) <= $length)
{
return $text;
}
// Set working length
$working_length = $length;
do
{
$truncated = truncate_text($text, $working_length, $truncate_string, $truncate_lastspace);
$stripped = strip_tags($truncated);
// Return truncation if no HTML is present in truncated text
if ($truncated == $stripped)
{
return $truncated;
}
// Increase truncation length to adjust for non-visible HTML tags
$working_length++;
// Redo truncation if visible (non-HTML) text length is less than target truncation length
}
while (strlen($stripped) < $length);
// Clean up HTML (unclosed tags, etc.)
$doc = new DOMDocument();
// Suppress parsing warnings with @ and wrap in <p></p> (to avoid weird behavior)
@$doc->loadHTML('<p>'. $truncated .'</p>', LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
// Return, removing <p></p>
return substr($doc->saveHTML(), 3, -5);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment