Trim text to 340 chars

前端 未结 9 897
情深已故
情深已故 2021-02-07 14:21

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

9条回答
  •  野性不改
    2021-02-07 14:48

    Why this way?

    • I like the regex solution over substring, to catch any other than whitespace word breaks (interpunction etc.)
    • John Condoe's solution is not perfectly correct, since it trim text to 340 characters and then finish the last word (so will often be longer than desired)

    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)
    • Exception is thrown in case given length was too small
    • \w\b part is to avoid whitespace or interpunction at the end (see 1 below)
    • In case first word would be longer than desired max length, that word will be brutally cut

    1. Despite the fact that in question result In the ... is described as desired, I feel In the... is more smooth (also don't like In the,... etc.)

提交回复
热议问题