In what ways can the PHP function nl2br() be utilized to handle line breaks and new lines in text data being stored in a database?

When storing text data in a database, line breaks and new lines can get lost or displayed as plain text when retrieved. To preserve these line breaks and new lines, the PHP function nl2br() can be used. This function converts new lines (\n) into HTML line breaks (<br>) so that the formatting is maintained when displaying the text.

// Example of using nl2br() when storing text data in a database
$text = &quot;This is a sample text with\na line break.&quot;;
$formatted_text = nl2br($text);

// Store $formatted_text in the database
// When retrieving the data, use htmlspecialchars_decode() to display the formatted text