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

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

    Ok so I got another version of this based on the above answers but taking more things in account(utf-8, \n and   ; ), also a line stripping the wordpress shortcodes commented if used with wp.

    function neatest_trim($content, $chars) 
      if (strlen($content) > $chars) 
      {
        $content = str_replace(' ', ' ', $content);
        $content = str_replace("\n", '', $content);
        // use with wordpress    
        //$content = strip_tags(strip_shortcodes(trim($content)));
        $content = strip_tags(trim($content));
        $content = preg_replace('/\s+?(\S+)?$/', '', mb_substr($content, 0, $chars));
    
        $content = trim($content) . '...';
        return $content;
      }
    

提交回复
热议问题