nl2br() : Inserting HTML Line breaks before all newlines in a string

Convert newlines to HTML line breaks

nl2br() inserts HTML <br> tags before newline characters. Escape untrusted text before applying nl2br() when displaying it as HTML.

$text = "Line one\nLine two";
echo nl2br(htmlspecialchars($text, ENT_QUOTES, 'UTF-8'));

The examples below show additional variations, expected output and practical usage.

$str="Welcome \n to plus2net";
echo nl2br($str);
Output
Welcome
to plus2net
Syntax
$string=nl2br($string);
To add line breaks in html we have to use <br> tags but to add this line break to any text entry from a form or from a text area we have to use the function nl2br() in PHP. The nl2br() function inserts an HTML line-break tag before newline characters in a string. This way we can automatically add line breaks for a web page inside a string. Here is the syntax of nl2br() function.

The most practical use of this is when users enter their data in a text area and then the details are displayed back to the visitors. Here if the visitor has used line breaks inside the text area then while displaying the details we have to take care of line breaks. When text entered in a textarea is displayed as HTML, nl2br() can preserve the user's line breaks.

Store the original textarea value, including its newline characters. Apply htmlspecialchars() and then nl2br() when rendering the value as HTML. This keeps stored data reusable for later editing and prevents submitted HTML from being executed.

Using PHP_EOL

Use PHP_EOL when generating platform-native text output such as files or command-line text.
echo 'This is text part'.PHP_EOL;
\n : Common newline on Linux / Unix
\r\n : Common newline on Windows
PHP_EOL resolves to the platform-specific end-of-line sequence.

Here is a demo of the use of this function. You can see how the data of the text area gets displayed with and without the line breaks. ( The only difference between the two is before displaying the second case nl2br() function is used. )


String Functions strip_tags() To remove HTML tags from a string


Subscribe to our YouTube Channel here



plus2net.com







vijay

19-12-2014

good one




PHP video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer