Truncating Strings in PHP to the Nearest Word
To crop a string at the end of the last word before a specified character count, PHP provides several methods.
Using wordwrap Function:
The wordwrap function divides text into multiple lines with a maximum width, automatically breaking at word boundaries. By taking only the first line, you can truncate the text to the nearest word:
$truncated_string = substr($string, 0, strpos(wordwrap($string, $desired_width), "\n"));
Edge Case Handling:
This method doesn't handle texts shorter than the desired width. For that, use the following:
if (strlen($string) > $desired_width) { $string = substr($string, 0, strpos(wordwrap($string, $desired_width), "\n")); }
Token Truncation:
To resolve potential issues with newlines in the text, this method splits the text into tokens (words, whitespace, and newlines) and accumulates their lengths:
function tokenTruncate($string, $desired_width) { $parts = preg_split('/([\s\n\r]+)/', $string, null, PREG_SPLIT_DELIM_CAPTURE); $length = 0; $last_part = 0; for (; $last_part < count($parts); ++$last_part) { $length += strlen($parts[$last_part]); if ($length > $desired_width) { break; } } return implode(array_slice($parts, 0, $last_part)); }
This method also handles UTF8 characters.
Unit Testing:
class TokenTruncateTest extends PHPUnit_Framework_TestCase { // ... test cases ... }
Additional Notes:
The above is the detailed content of How Can I Truncate Strings in PHP to the Nearest Word?. For more information, please follow other related articles on the PHP Chinese website!