This is the function Drupal uses to shorten strings without breaking up words.
//$wordsafe: set to TRUE to not truncate in middle of words
//$dots: set to TRUE to add " ..." to the end of the truncated string
function truncate_utf8($string, $len, $wordsafe = FALSE, $dots = FALSE) {
if (strlen($string) <= $len) {
return $string;
}
if ($dots) {
$len -= 4;
}
if ($wordsafe) {
$string = substr($string, 0, $len + 1); // leave one more character
if ($last_space = strrpos($string, ' ')) { // space exists AND is not on position 0
$string = substr($string, 0, $last_space);
}
else {
$string = substr($string, 0, $len);
}
}
else {
$string = substr($string, 0, $len);
}
if ($dots) {
$string .= ' ...';
}
return $string;
}