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 ...
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 ...
try:
preg_match('/^.{0,340}(?:.*?)\b/siu', $text, $matches);
echo $matches[0] . '...';
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, ' ')) . " ...";
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.
you can try using functions that comes with PHP , such as wordwrap
print wordwrap($text,340) . "...";