2 2 Votes

PHP: Convert Line Breaks from Textarea in HTML Line Breaks

Tip by Computer Expert | 20/01/2012 at 17:46

We have a textarea, that can be filled out by the visitors of our website. After that, the data will be sent via POST to our script and we would like to print the data from the textarea once again on our page.

However, when doing this, a small problem occurs: All of the new lines from the textarea will no longer be visible in our HTML document when we are printing them as they are. The reason is simple: line breaks from the source code will not be displayed in the browser, like it is also with the line breaks you enter in your HTML editor.

The solution is the following function, which is available directly in PHP:

$str = $_POST['text'];
//or
$str = "Test 1 \r\n Test 2 \n\r Test 3 \r";
 
echo nl2br($str);

With the function nl2br(), all kinds of line breaks such as \r\n, \n\r or \r will be converted to "<br />", so that the line breaks will also be visible in the browser. The output of the example is the following:

Test 1 <br />
Test 2 <br />
Test 3 <br />

This saves long search and replace functions.

ReplyPositiveNegative

About the Author

Avatar AuthorThe author has not added a short description to his profile yet.
Show Profile | Message

 

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own articles on askingbox.com. How to do.