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
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.)