Possible Duplicate:
How to Truncate a string in PHP to the word closest to a certain number of characters?
How can I shorten a string to a maximum of 140 chars without slicing through a word.
Take the following string:
$string = "This is an example string that contains more than 140 characters. If I use PHPs substring function it will split it in the middle of this word."
Using substr($string, 0, 140)
we would get something like this:
This is an example string that contains more than 140 characters. If I use PHPs substring function it will split it in the middle of this wo
Notice it sliced through the word "word".
What I need is to be able to shorten a string while preserving entire words but without going over 140 characters.
I did find the following code but even though it will preserve entire words, it does not guarantee that the entire string does not go over the 140 char limit:
function truncate($text, $length) {
$length = abs((int)$length);
if(strlen($text) > $length) {
$text = preg_replace("/^(.{1,$length})(\s.*|$)/s", '\\1...', $text);
}
return($text);
}