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.
nl2br() can preserve the user's line breaks.
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.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 PHP_EOL resolves to the platform-specific end-of-line sequence.Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.
| vijay | 19-12-2014 |
| good one | |