Skip to content

Instantly share code, notes, and snippets.

@AriaMinaei
Created May 25, 2011 16:32
Show Gist options
  • Save AriaMinaei/991308 to your computer and use it in GitHub Desktop.
Save AriaMinaei/991308 to your computer and use it in GitHub Desktop.
<?php
/**
* Truncates a text without breaking the last word.
* @param String $text
* @param Int $length
* @param String $lastString
* @return String
*/
function safe_truncate_text($text, $length = 160, $lastString = '...')
{
$text = trim($text);
$words = explode(' ', $text);
$finalWords = array();
$finalLength = 0;
foreach ($words as $word) {
if ($finalLength + strlen($word) <= $length) {
$finalWords[] = $word;
$finalLength += strlen($word) + 1;
} else {
break;
}
}
$finalString = implode(' ', $finalWords);
return $finalString ? $finalString . $lastString : '';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment