Category: PHP5

Added: 21st of December 2015

Viewed: 3746 times

Preserve line breaks in PHP. nl2br function

If your website allows users to enter information via a textbox, chances are they going to enter new lines as they enter their text. The problem is when you output this information, the line breaks will not be preserved.

To solve this issue in PHP, we can the use the nl2br function. The nl2br() function inserts HTML line breaks (<br />) in front of each newline (n) in a string.

In the example below, we presume that the user has just entered some text via a textbox on your website.

To preserve the line breaks you would use the following php code below.

<?php
echo nl2br($_POST['textarea']);
?>

If you are outputting information via your database, you would use the following code.
<?php
echo nl2br($row['textarea']);
?>


Other Tips & Tutorials

PHP5

Convert all characters to Upper or Lower case in PHP5

Posted: 7th of October 2020

Views: 212

PHP5

Get the day of the week for a specified date using PHP5

Posted: 17th of January 2016

Views: 1855

PHP5

How to upload files larger than 2MB using PHP5

Posted: 14th of January 2016

Views: 2012

PHP5

Preserve line breaks in PHP. nl2br function

Posted: 21st of December 2015

Views: 3746

PHP5

Convert a Unix timestamp to date and time using PHP

Posted: 18th of December 2015

Views: 2127

PHP5

How to validate a form using PHP5

Posted: 15th of December 2015

Views: 1101

PHP5

Count the number of elements in a PHP array using the count() function

Posted: 15th of December 2015

Views: 963

PHP5

Pass ampersand through query strings in URL using PHP5

Posted: 27th of November 2015

Views: 2267