[PHP quickie] Select a certain number of words from a string
An alternative to subst() that selects entire words rather than a specified number of characters. I used this on a recent project where I needed to create a meta tag description from text and HTML stored in a database.
Uses PHP’s native str_word_count() function.
function select_number_of_words($input,$number_of_words){
$output = '';
$input = strip_tags($input);
$input = str_word_count($input,1); // second parameter returns the string as an array.
for($i=0; $i< $number_of_words; $i++){
$output .=$input[$i].' ';
}
return trim($output); // cut off the last space.
}