Skip to content
PHP Logo

How can the nl2br function in PHP help in displaying text with line breaks correctly on a webpage?

When displaying text with line breaks on a webpage, simply using the newline character (\n) may not work as expected in HTML. The nl2br function in PHP can help by converting newline characters (\n) to HTML line breaks (<br>) so that the text is displayed correctly with line breaks on the webpage.

php
$text_with_line_breaks = "This is a text with\nline breaks.";
echo nl2br($text_with_line_breaks);