A handy little function for your bag of tricks. This PHP function will return a max number of words out of a string, or the whole string if it’s already shorter.
/**
* Returns the first $wordsreturned out of $string. If string
* contains more words than $wordsreturned, the entire string
* is returned.
* @param String $string The string to check
* @param int $wordsreturned Max number of words to include
*/
function shorten_string($string, $wordsreturned)
{
$retval = $string;
$array = explode(' ', $string);
if (count($array)<= $wordsreturned) {
$retval = $string;
}
else {
array_splice($array, $wordsreturned);
$retval = implode(' ', $array).' ...';
}
return $retval;
}
This probably could be made shorter, but I was in a hurry when I needed this and went for quick rather than clever.
[…] does us a couple of other functions from my bag of tricks. The days_ago and shorten_string functions are used to make everything a bit […]