How can you limit the display of a text to a certain number of characters in PHP?
To limit the display of a text to a certain number of characters in PHP, you can use the `substr()` function to extract a portion of the text and then add an ellipsis (...) at the end if the text exceeds the limit. This is useful for displaying previews or summaries of longer texts without overwhelming the user.
function limit_text($text, $limit) {
if (strlen($text) > $limit) {
$text = substr($text, 0, $limit);
$text = substr($text, 0, strrpos($text, ' ')) . '...';
}
return $text;
}
// Example usage
$text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
$limited_text = limit_text($text, 20);
echo $limited_text; // Output: Lorem ipsum dolor...