nice functional piece of code. just to clean this up a little, why not put it in a function?
function limitwords($string,$max,$trail='')
{
$max--;
$tmp = '';
$string = trim($string);
$word = explode(" ", $string);
$total_words = count($word);
if ($total_words > $max) {
for ($i = 0; $i <= $max; $i++) {
if ($i == $max) {
$tmp .= $word[$max].$trail;
} else {
$tmp .= $word[$i]." ";
}
}
} else {
$tmp = $string;
}
return $tmp;
}
ive also fixed an error where it seems you forgot that array indexes start at 0 (notice the $max--😉, i also thought it would be a good idea to have the trail as an argument. this way, you could easily put a link or something in there. eg;
echo limitwords('here is a small snippet of an article',4,'<a href="more.php?id=2">read more</a>');