Get Only n Words From String

written by Arief Bayu Purwanto on February 3, 2010 in snippet with 10 comments

Here’s the code:

function trim_word( $words, $howmany = 1){
	$x = explode(" ", $words);
	if(count( $x) <=$howmany ){
		return $words;
	} else {
		return implode(" ", array_slice( $x, 0, $howmany));
	}
}

Here’s the output:

$words = "this is string that is long enough that I want to trim it.";


echo trim_word($words, 10) . "\n";
//this will echo: this is string that is long enough that I want

UPDATE:

  1. 2010-02-05 15:03:25 – Fixing $howmany usage. Sorry, for the inconvenience:D