Trim text to 340 chars

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

    If you have the mbstring extension enabled (which is on most servers nowadays), you can use the mb_strimwidth function.

    echo mb_strimwidth($string, 0, 340, '...');
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-07 15:04

    It seems like you would want to first trim the text down to 340 characters exactly, then find the location of the last ' ' in the string and trim down to that amount. Like this:

    $string = substr($string, 0, 340);
    $string = substr($string, 0, strrpos($string, ' ')) . " ...";
    
    0 讨论(0)
提交回复
热议问题