How to show line breaks on a page
Short answer
A browser does not show line breaks. nl2br() adds a <br> tag before them:
<?php
echo nl2br("First line\nSecond line");Output:
First line<br />
Second lineText from a user
Escape the text first and add the tags afterwards — otherwise the <br> tags get escaped too:
<?php
$comment = "Nice <b>post</b>!\nThanks";
echo nl2br(htmlspecialchars($comment));Output:
Nice <b>post</b>!<br />
ThanksParagraphs
An empty line between parts of the text marks a paragraph:
<?php
$text = "First paragraph.\n\nSecond paragraph.";
foreach (preg_split('/\n{2,}/', $text) as $paragraph) {
echo '<p>', htmlspecialchars($paragraph), "</p>\n";
}Output:
<p>First paragraph.</p>
<p>Second paragraph.</p>Functions used in this recipe
- nl2br — Inserts a br tag before every line break.
- htmlspecialchars — Replaces HTML special characters with safe entities.
- explode — Splits a string into an array by a separator.