Tiffany B. Brown

a mish-mosh of stuff

[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.
}
  • Stephen

    Instead of that for loop (though there's nothing wrong with it), I think it might look cleaner to use:
    array_slice($input,0,$number_of_words);
    and
    implode(" ",$input);

  • Stephen

    Instead of that for loop (though there's nothing wrong with it), I think it might look cleaner to use:
    array_slice($input,0,$number_of_words);
    and
    implode(" ",$input);