Are there any PHP functions or libraries available for handling text truncation and display ellipses?
When displaying text on a webpage, it is common to truncate long text and add an ellipsis (...) at the end to indicate that the text has been cut off. This can be achieved in PHP using the `mb_strimwidth()` function to truncate the text to a specified length and then adding the ellipsis if the text exceeds that length.
function truncateText($text, $length) {
if (mb_strlen($text) > $length) {
$truncatedText = mb_strimwidth($text, 0, $length, '...');
return $truncatedText;
} else {
return $text;
}
}
// Example usage
$text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
$truncatedText = truncateText($text, 20);
echo $truncatedText; // Output: Lorem ipsum dolor si...
Related questions
-
scanning directories PHP modification date
-
PHP array manipulation string functions
-
Factory pattern PHP class instances database connections