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 las
I put the answer of John Conde in a method:
function softTrim($text, $count, $wrapText='...'){
if(strlen($text)>$count){
preg_match('/^.{0,' . $count . '}(?:.*?)\b/siu', $text, $matches);
$text = $matches[0];
}else{
$wrapText = '';
}
return $text . $wrapText;
}
Examples:
echo softTrim("Lorem Ipsum is simply dummy text", 10);
/* Output: Lorem Ipsum... */
echo softTrim("Lorem Ipsum is simply dummy text", 33);
/* Output: Lorem Ipsum is simply dummy text */
echo softTrim("LoremIpsumissimplydummytext", 10);
/* Output: LoremIpsumissimplydummytext... */