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

前端 未结 27 1126
猫巷女王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:12

    Based on @Justin Poliey's regex:

    // Trim very long text to 120 characters. Add an ellipsis if the text is trimmed.
    if(strlen($very_long_text) > 120) {
      $matches = array();
      preg_match("/^(.{1,120})[\s]/i", $very_long_text, $matches);
      $trimmed_text = $matches[0]. '...';
    }
    

提交回复
热议问题