Trim text to 340 chars

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

    The other answers show you how you can make the text roughly 340 characters. If that's fine for you, then use one of the other answers.

    But if you want a very strict maximum of 340 characters, the other answers won't work. You need to remember that adding the '...' can increase the length of the string and you need to take account of that.

    $max_length = 340;
    
    if (strlen($s) > $max_length)
    {
        $offset = ($max_length - 3) - strlen($s);
        $s = substr($s, 0, strrpos($s, ' ', $offset)) . '...';
    }
    

    Note also that here I'm using the overload of strrpos that takes an offset to start searching directly from the correct location in the string, rather than first shortening the string.

    See it working online: ideone

提交回复
热议问题