Truncating PHP Strings to the Nearest Word
Truncating a string to a specific character limit can result in an unsightly cutoff mid-word. To cater to this need, we explore a PHP code snippet that accurately truncates text at the end of the closest word.
Solution 1: Using Wordwrap
The wordwrap function can split text into lines based on the specified maximum width, breaking at word boundaries. To achieve the desired truncation, we can simply utilize the first line from the split text:
$truncated = substr($string, 0, strpos(wordwrap($string, $limit), "\n"));
Solution 2: Token-Based Truncation
However, solution 1 has a limitation: it prematurely cuts the text if a newline character appears before the cutoff point. To mitigate this, we can implement token-based truncation:
function tokenTruncate($string, $limit) { $tokens = preg_split('/([\s\n\r]+)/u', $string, null, PREG_SPLIT_DELIM_CAPTURE); $length = 0; $lastToken = 0; while ($length <= $limit && $lastToken < count($tokens)) { $length += strlen($tokens[$lastToken]); $lastToken++; } return implode(array_slice($tokens, 0, $lastToken)); }
Conclusion
By implementing these solutions, you can effectively truncate PHP strings at the nearest word, ensuring a clean and meaningful display.
The above is the detailed content of How Can I Truncate PHP Strings to the Nearest Word Without Mid-Word Cuts?. For more information, please follow other related articles on the PHP Chinese website!