Trim text to 340 chars

前端 未结 9 899
情深已故
情深已故 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:41

    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... */
    

提交回复
热议问题