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

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

    It's surprising how tricky it is to find the perfect solution to this problem. I haven't yet found an answer on this page that doesn't fail in at least some situations (especially if the string contains newlines or tabs, or if the word break is anything other than a space, or if the string has UTF-8 multibyte characters).

    Here is a simple solution that works in all cases. There were similar answers here, but the "s" modifier is important if you want it to work with multi-line input, and the "u" modifier makes it correctly evaluate UTF-8 multibyte characters.

    function wholeWordTruncate($s, $characterCount) 
    {
        if (preg_match("/^.{1,$characterCount}\b/su", $s, $match)) return $match[0];
        return $s;
    }
    

    One possible edge case with this... if the string doesn't have any whitespace at all in the first $characterCount characters, it will return the entire string. If you prefer it forces a break at $characterCount even if it isn't a word boundary, you can use this:

    function wholeWordTruncate($s, $characterCount) 
    {
        if (preg_match("/^.{1,$characterCount}\b/su", $s, $match)) return $match[0];
        return mb_substr($return, 0, $characterCount);
    }
    

    One last option, if you want to have it add ellipsis if it truncates the string...

    function wholeWordTruncate($s, $characterCount, $addEllipsis = ' …') 
    {
        $return = $s;
        if (preg_match("/^.{1,$characterCount}\b/su", $s, $match)) 
            $return = $match[0];
        else
            $return = mb_substr($return, 0, $characterCount);
        if (strlen($s) > strlen($return)) $return .= $addEllipsis;
        return $return;
    }
    

提交回复
热议问题