What are the best practices for handling text length limitations in PHP to maintain a visually appealing design?
When dealing with text length limitations in PHP to maintain a visually appealing design, it is important to implement truncation or ellipsis to ensure that text does not overflow its container. One common approach is to limit the text length and add an ellipsis (...) at the end to indicate that there is more content. This helps maintain a clean and organized design while still providing users with the option to view the full text if needed.
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;