Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trim text to 340 chars

Tags:

php

ellipsis

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 ...
like image 235
CLiown Avatar asked Jan 20 '10 20:01

CLiown


2 Answers

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, ' ')) . " ...";
like image 120
Nicholas Flynt Avatar answered Nov 08 '22 07:11

Nicholas Flynt


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

like image 26
Mark Byers Avatar answered Nov 08 '22 06:11

Mark Byers