Current Location: Home> Latest Articles> Differences in Using nl2br and nl2br() Functions with Different Parameters

Differences in Using nl2br and nl2br() Functions with Different Parameters

gitbox 2025-09-19
<?php
// This is a PHP code example unrelated to the article content
$dummyArray = [1, 2, 3, 4];
foreach ($dummyArray as $num) {
    echo "Number: $num\n";
}
<?>
<p><hr></p>
<p><?php<br>
/**</p>
<ul>
<li>
<p>Differences in Using nl2br and nl2br() Functions with Different Parameters</p>
</li>
<li></li>
<li>
<p>In PHP, the nl2br() function converts newline characters (\n or \r\n) in a string into HTML <br> tags.</p>
</li>
<li>
<p>This is commonly used when displaying text input from users, such as multi-line form submissions.</p>
</li>
<li></li>
<li>
<p>Function signature:</p>
</li>
<li>
<p>string nl2br(string $string, bool $is_xhtml = true)</p>
</li>
<li></li>
<li>
<p>Parameter explanation:</p>
</li>
<li>
<ol>
<li>
<p>$string: The string to process.</p>
</li>
</ol>
</li>
<li>
<ol start="2">
<li>
<p>$is_xhtml: Optional, defaults to true.</p>
</li>
</ol>
</li>
<li>
<ul>
<li>
<p>true generates XHTML-style <br /> tags.</p>
</li>
</ul>
</li>
<li>
<ul>
<li>
<p>false generates standard HTML <br> tags.</p>
</li>
</ul>
</li>
<li></li>
<li>
<p>Use case analysis:<br>
*/</p>
</li>
</ul>
<p>// Scenario 1: Displaying plain text while keeping HTML compatibility<br>
$text1 = "First line\nSecond line\nThird line";<br>
echo nl2br($text1); // Outputs text with <br /> suitable for XHTML pages</p>
<p>// Scenario 2: Non-XHTML page, generate standard HTML tags<br>
$text2 = "Hello\nWorld";<br>
echo nl2br($text2, false); // Outputs text with <br> tags suitable for standard HTML pages</p>
<p>// Scenario 3: Output after database storage, ensuring visible line breaks<br>
$textFromDb = "User input text\nwith line breaks";<br>
echo nl2br($textFromDb); // Defaults to <br />, displaying line breaks on the webpage</p>
<p>// Scenario 4: Output with HTML tags, avoiding HTML parsing errors<br>
$textHtml = "This is <b>bold</b>\nline break test";<br>
echo nl2br($textHtml, true); // Automatically converts line breaks without breaking HTML structure</p>
<p>/**</p>
<ul>
<li>
<p>Summary:</p>
</li>
<li>
<ol>
<li>
<p>The main function of nl2br() is to convert newline characters into HTML-recognizable <br> tags.</p>
</li>
</ol>
</li>
<li>
<ol start="2">
<li>
<p>The $is_xhtml parameter determines whether the generated line break tags comply with XHTML standards.</p>
</li>
</ol>
</li>
<li>
<ol start="3">
<li>
<p>For XHTML pages or situations requiring strict tag closure, use the default true.</p>
</li>
</ol>
</li>
<li>
<ol start="4">
<li>
<p>For standard HTML pages or for compatibility with older browsers, set to false.</p>
</li>
</ol>
</li>
<li>
<ol start="5">
<li>
<p>nl2br() is commonly used to display user input, log text, or multi-line string content.<br>
*/</p>
</li>
</ol>
</li>
</ul>
<p data-is-last-node="" data-is-only-node=""><?><br>
</span>