Trim headline to nearest word

后端 未结 6 1860
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-06 19:45

Say for example I have the following code:

My very long title

Another long title

If I wanted to

6条回答
  •  余生分开走
    2020-12-06 20:19

    This is easy using a PHP function. Look at this example:

    function trim_text($input, $length) {
    
        // If the text is already shorter than the max length, then just return unedited text.
        if (strlen($input) <= $length) {
            return $input;
        }
    
        // Find the last space (between words we're assuming) after the max length.
        $last_space = strrpos(substr($input, 0, $length), ' ');
        // Trim
        $trimmed_text = substr($input, 0, $last_space);
        // Add ellipsis.
        $trimmed_text .= '...';
    
        return $trimmed_text;
    }
    

    You can then pass in text with a function like:

    trim_text('My super long title', 10);

    (I haven't tested this, but it should work perfectly.)

提交回复
热议问题