Trim text to 340 chars

前端 未结 9 915
情深已故
情深已故 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 15:01

    function trim_characters( $text, $length = 340 ) {

    $length = (int) $length;
    $text = trim( strip_tags( $text ) );
    
    if ( strlen( $text ) > $length ) {
        $text = substr( $text, 0, $length + 1 );
        $words = preg_split( "/[\s]| /", $text, -1, PREG_SPLIT_NO_EMPTY );
        preg_match( "/[\s]| /", $text, $lastchar, 0, $length );
        if ( empty( $lastchar ) )
            array_pop( $words );
    
        $text = implode( ' ', $words ); 
    }
    
    return $text;
    

    }

    Use this function trim_characters() to trims a string of words to a specified number of characters, gracefully stopping at white spaces. I think this is helpful to you.

提交回复
热议问题