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... */
try:
preg_match('/^.{0,340}(?:.*?)\b/siu', $text, $matches);
echo $matches[0] . '...';
you can try using functions that comes with PHP , such as wordwrap
print wordwrap($text,340) . "...";
Simplest solution
$text_to_be_trim= "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry standard.";
if(strlen($text_to_be_trim) > 20)
$text_to_be_trim= substr($text_to_be_trim,0,20).'....';
For multi-byte text
$stringText= "UTIL CONTROL DISTRIBUCION AMARRE CIGÜEÑAL";
$string_encoding = 'utf8';
$s_trunc = mb_substr($stringText, 0, 37, $string_encoding);
echo $s_trunc;
Why this way?
Actual regex solution is very simple:
/^(.{0,339}\w\b)/su
Full method in PHP could look like this:
function trim_length($text, $maxLength, $trimIndicator = '...')
{
if(strlen($text) > $maxLength) {
$shownLength = $maxLength - strlen($trimIndicator);
if ($shownLength < 1) {
throw new \InvalidArgumentException('Second argument for ' . __METHOD__ . '() is too small.');
}
preg_match('/^(.{0,' . ($shownLength - 1) . '}\w\b)/su', $text, $matches);
return (isset($matches[1]) ? $matches[1] : substr($text, 0, $shownLength)) . $trimIndicator ;
}
return $text;
}
More explanation:
$shownLength
is to keep very strict limit (like Mark Byers mentioned)\w\b
part is to avoid whitespace or interpunction at the end (see 1 below)In the ...
is described as desired, I feel In the...
is more smooth (also don't like In the,...
etc.)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