Skip to content
PHP Logo

Are there any best practices for handling text truncation in PHP to ensure the desired output?

When truncating text in PHP, it is important to consider the desired output length and how to handle different cases such as preserving whole words or adding ellipses for indication of truncation. One common approach is to use the `mb_strimwidth()` function which allows you to truncate a string while ensuring it remains within a specified length.

php
function truncateText($text, $length, $ellipsis = '...') {
    if (mb_strlen($text) <= $length) {
        return $text;
    }
    
    return mb_strimwidth($text, 0, $length, $ellipsis);
}

// Example usage
$text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
$truncatedText = truncateText($text, 20);
echo $truncatedText; // Output: "Lorem ipsum dolor..."