Replacing Newline Characters with HTML Line Breaks
When attempting to replace newline or \r\n characters with HTML line breaks, some common methods may not yield the desired results, particularly when dealing with double newlines (\r\r).
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:
// Won't work
$desc = 'Line one\nline two';
// Should work
$desc2 = "Line one\nline two";
echo nl2br($desc);
echo '
';
echo nl2br($desc2);
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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3