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

前端 未结 27 1633
猫巷女王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 07:57

    I would use the preg_match function to do this, as what you want is a pretty simple expression.

    $matches = array();
    $result = preg_match("/^(.{1,199})[\s]/i", $text, $matches);
    

    The expression means "match any substring starting from the beginning of length 1-200 that ends with a space." The result is in $result, and the match is in $matches. That takes care of your original question, which is specifically ending on any space. If you want to make it end on newlines, change the regular expression to:

    $result = preg_match("/^(.{1,199})[\n]/i", $text, $matches);
    

提交回复
热议问题