tags:

views:

53

answers:

2

i am using substr to trim the first 100 characters from the string. however i need a function that can trim a particular number of words, instead of characters from a string?

$trimmed_details = substr($row->details, 0, 200).'...';

is there a built in function to do that?

+1  A: 

Try this:

join(" ", explode(" ", $yourStr, 100));
Andrew Hare
`join` is just an alias, better use `implode`. IMHO it blends better with the `explode`. Moreover, take this into account: "If limit (third parameter of explode) is set and positive, the returned array will contain a maximum of limit elements with the last element containing the rest of string." - you'd have to get rid of the last one.
middus
how do i get rid of the last one?
amit
You can combine explode with array_slice(). Something like this:implode(" ", array_slice( explode(" ", $yourStr, 101), 0, 100) );
Nycto
+1  A: 

No, there is no builtin function in both PHP and mysql. Because there is no data type "word (of language)" in the either system. You can invent some regexp to do this, but I'd avise to just give up and use old char-based trimming.

Col. Shrapnel