Skip to content
PHP Logo

How can PHP developers ensure that line breaks are properly displayed in <textarea> elements without confusing users with <br> tags?

When displaying text from a database in a <textarea> element, PHP developers can ensure that line breaks are properly displayed by using the PHP function nl2br(). This function converts newlines (\n) in a string to HTML line breaks (<br>). By applying nl2br() to the text before populating the <textarea>, developers can maintain the line breaks without confusing users with visible <br> tags.

php
$text_from_database = "This is a text with\nline breaks.";
$text_for_textarea = nl2br($text_from_database);
echo '<textarea>' . $text_for_textarea . '</textarea>';