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 ...
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, ' ')) . " ...";
The other answers show you how you can make the text roughly 340 characters. If that's fine for you, then use one of the other answers.
But if you want a very strict maximum of 340 characters, the other answers won't work. You need to remember that adding the '...'
can increase the length of the string and you need to take account of that.
$max_length = 340;
if (strlen($s) > $max_length)
{
$offset = ($max_length - 3) - strlen($s);
$s = substr($s, 0, strrpos($s, ' ', $offset)) . '...';
}
Note also that here I'm using the overload of strrpos
that takes an offset to start searching directly from the correct location in the string, rather than first shortening the string.
See it working online: ideone
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With