Home > Article > Backend Development > Why Doesn\'t `nl2br()` Replace Newlines in My PHP Code?
Replacing Newline Characters with HTML Line Breaks
When attempting to replace newline or rn characters with HTML line breaks, some common methods may not yield the desired results, particularly when dealing with double newlines (rr).
Issue and Investigation:
The initial attempts included using preg_replace(), str_replace(), and nl2br(). However, the newlines persisted, raising the question of whether double newlines caused the problem.
Solution and Explanation:
The nl2br() function should suffice for inserting line breaks before new line characters. However, if it doesn't work, ensure that the text being processed is enclosed in double quotes.
Example:
<code class="php">// Won't work $desc = 'Line one\nline two'; // Should work $desc2 = "Line one\nline two"; echo nl2br($desc); echo '<br/>'; echo nl2br($desc2);</code>
Additional Insight:
Single quotes do not interpret escape sequences like n, while double quotes do. Hence, using single quotes for the text may hinder the replacement process.
The above is the detailed content of Why Doesn\'t `nl2br()` Replace Newlines in My PHP Code?. For more information, please follow other related articles on the PHP Chinese website!