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

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

    The following solution was born when I've noticed a $break parameter of wordwrap function:

    string wordwrap ( string $str [, int $width = 75 [, string $break = "\n" [, bool $cut = false ]]] )

    Here is the solution:

    /**
     * Truncates the given string at the specified length.
     *
     * @param string $str The input string.
     * @param int $width The number of chars at which the string will be truncated.
     * @return string
     */
    function truncate($str, $width) {
        return strtok(wordwrap($str, $width, "...\n"), "\n");
    }
    

    Example #1.

    print truncate("This is very long string with many chars.", 25);
    

    The above example will output:

    This is very long string...
    

    Example #2.

    print truncate("This is short string.", 25);
    

    The above example will output:

    This is short string.
    

提交回复
热议问题