22 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'];
$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.


About the Author

AvatarThe author has not added a profile short description yet.
Show Profile


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.


Ask your own question or write your own article on askingbox.com. That’s how it’s done.