Skip to content
PHP Logo

What alternative function was suggested to the user to truncate text while preserving words in PHP?

The issue is truncating text in PHP while preserving whole words. One alternative function that can be used is `mb_strimwidth()`. This function allows you to specify the desired width of the truncated string while ensuring that it ends on a whole word boundary.

php
$text = "This is a sample text that needs to be truncated while preserving whole words.";
$truncated_text = mb_strimwidth($text, 0, 30, '...');
echo $truncated_text;