How can PHP be optimized to efficiently handle text truncation with line breaks in a database-driven application like a guestbook?
When handling text truncation with line breaks in a database-driven application like a guestbook, one approach is to use PHP's `wordwrap()` function to break the text into lines of a specified length while preserving the line breaks. This can help ensure that the truncated text remains readable and visually appealing.
// Function to truncate text with line breaks
function truncateTextWithLineBreaks($text, $length) {
// Break the text into lines of specified length while preserving line breaks
$wrappedText = wordwrap($text, $length, "\n", true);
// Get the first line of the wrapped text
$truncatedText = explode("\n", $wrappedText)[0];
return $truncatedText;
}
// Example usage
$text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.";
$truncatedText = truncateTextWithLineBreaks($text, 30);
echo $truncatedText;