tags:

views:

303

answers:

4

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 ...
+3  A: 

try:

preg_match('/^.{0,340}(?:.*?)\b/siu', $text, $matches);
echo $matches[0] . '...';
John Conde
By default, the `.` does not match line breaks. So when there are line breaks before the 340th character, it will not work. Adding a `s` modifier in the end will do the trick.
Bart Kiers
Thanks, Bart. Done.
John Conde
+10  A: 

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, ' ')) . " ...";
Nicholas Flynt
Ya beat me to it.
KingRadical
Needs some polish (check if string needs to get shortened, etc) but short and sweet.
Infinity
A: 

If the string is too long, first use substr to truncate the string first and then a regular expression to remove the last full or partial word:

$s = substr($s, 0, 337);
$s = preg_replace('/ [^ ]*$/', ' ...', $s);

Note that you have to make the original string shorter than 340 bytes because when you add the ... this could increase the length of the string beyond 340 bytes.

Mark Byers
A: 

you can try using functions that comes with PHP , such as wordwrap

print wordwrap($text,340) . "...";
ghostdog74