You could use strrpos to find the last space character in the string:
function truncate($text, $length = 140) {
if(strlen($text) > $length) {
// $length - strlen($text) is used to find the last occurrence of a blank
// UP TO the $length character in the string.
$text = substr($text, 0, strrpos($text,' ', $length - strlen($text) ));
}
return $text;
}
It wouldn't add ...
though. For this to work you can change the function to:
function truncate($text, $length = 140) {
if(strlen($text) > $length) {
$text = substr($text, 0, strrpos($text,' ', $length - strlen($text)-3)) . '...';
}
return $text;
}