How to Truncate a string in PHP to the word closest to a certain number of characters?

前端 未结 27 1463
猫巷女王i
猫巷女王i 2020-11-22 07:28

I have a code snippet written in PHP that pulls a block of text from a database and sends it out to a widget on a webpage. The original block of text can be a lengthy artic

27条回答
  •  不要未来只要你来
    2020-11-22 08:15

    $shorttext = preg_replace('/^([\s\S]{1,200})[\s]+?[\s\S]+/', '$1', $fulltext);
    

    Description:

    • ^ - start from beginning of string
    • ([\s\S]{1,200}) - get from 1 to 200 of any character
    • [\s]+? - not include spaces at the end of short text so we can avoid word ... instead of word...
    • [\s\S]+ - match all other content

    Tests:

    1. regex101.com let's add to or few other r
    2. regex101.com orrrr exactly 200 characters.
    3. regex101.com after fifth r orrrrr excluded.

    Enjoy.

提交回复
热议问题