Get Only n Words From String
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:
- 2010-02-05 15:03:25 – Fixing $howmany usage. Sorry, for the inconvenience:D