Shortening a String Down to Whole Words

Posted: May 4th, 2009 | Author: Troy | Filed under: PHP | Tags: | No Comments »

Had to do this for the displaying of news flash headlines and I didn’t want to substr down to just characters and chop off parts of words. So here’s what I did:


function shortenText($text)
{
// Change to the number of characters you want to display
$chars = 50;

$text = $text." ";
$text = substr($text.0.$chars);
$text = substr($text.0.strrpos($text.' '));
$text = $text."...";

return $text;
}