Trim headline to nearest word

后端 未结 6 1803
佛祖请我去吃肉
佛祖请我去吃肉 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:37

    Maybe you're searching for wordwrap().

    string wordwrap ( string $str [, int $width = 75 [, string $break = "\n" [, bool $cut = false ]]] )
    

    Use $break to break the line using the optional break parameter. If the cut is set to TRUE, the string is always wrapped at or before the specified width. So if you have a word that is larger than the given width, it is broken apart.

    Check out function documentation on php's site for more examples.

    +++

    Another solution would be to split title by ' ' (a space) using explode() and provide a limit to say max 5 words, than cut off the last element of array using array_pop and finally joining them with implode() using ' ' (that space) as glue. But this solution is not the best as it will give you ugly output if you have long words.

提交回复
热议问题