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
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.