How can PHP be used to format text retrieved from a database?

To format text retrieved from a database using PHP, you can use functions like nl2br() to convert newlines to HTML line breaks, htmlspecialchars() to encode special characters, and trim() to remove any leading or trailing white spaces. By applying these functions to the retrieved text before displaying it on a webpage, you can ensure proper formatting and prevent any potential security vulnerabilities.

// Assuming $text contains the text retrieved from the database
$formattedText = nl2br(htmlspecialchars(trim($text)));

echo $formattedText;