Trim text to 340 chars

CLiown picture CLiown · Jan 20, 2010 · Viewed 36.8k times · Source

I'm pulling blog posts from a DB. I want to trim the text to a max length of 340 characters.

If the blog post is over 340 characters I want to trim the text to the last full word and add '...' on the end.

E.g.

NOT: In the begin....

BUT: In the ...

Answer

Nicholas Flynt picture Nicholas Flynt · Jan 20, 2010

It seems like you would want to first trim the text down to 340 characters exactly, then find the location of the last ' ' in the string and trim down to that amount. Like this:

$string = substr($string, 0, 340);
$string = substr($string, 0, strrpos($string, ' ')) . " ...";