Skip to content

Instantly share code, notes, and snippets.

@sonnyt
Last active August 29, 2015 13:57
Show Gist options
  • Save sonnyt/9775861 to your computer and use it in GitHub Desktop.
Save sonnyt/9775861 to your computer and use it in GitHub Desktop.
Proper Truncation
<?php
function truncate($text, $limit = 150, $elips = '...')
{
$text = html_entity_decode($text, ENT_COMPAT | ENT_HTML401, 'UTF-8');
$len = strlen($text);
if ($len > $limit) {
preg_match('/(.{' . $limit . '}.*?)\b/', $text, $matches);
$text = rtrim($matches[1]) . $elips;
}
return htmlentities($text, ENT_COMPAT | ENT_HTML401, 'UTF-8');
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment