I have this code for saving line breaks in text area input to database:
$input = preg_replace("/(\n)+/m", '\n', $input);
On examining the input in the database, the line breaks are actually saved.
But the problem is when I want to echo it out, the line breaks do not appear
in the output, how do I preserve the line breaks in input and also echo them
out. I don't want to use <pre></pre>
.
You are replacing actual sequences of newlines in the $input
with the literal two character sequence \n
(backslash + n) - not a newline. These need to be converted back to newlines when read from the database. Although I suspect you intend to keep these actual newlines in the database and should be using a double quoted string instead...
$input = preg_replace('/(\n)+/m', "\n", $input);
Note that I have replaced the first string delimiters with single quotes and the second string with double quotes. \n
is a special sequence in a regular expression to indicate a newline (ASCII 10), but it is also a character escape in PHP to indicate the same - the two can sometimes conflict.
I think PHP has the solution:
nl2br
— Inserts HTML line breaks before all newlines in a string
Edit: You may need to replace CR / LF to make it work properly.
// Convert line endings to Unix style (NL)
$input = str_replace(array("\r\n", "\r"), "\n", $input);
// Remove multiple lines
$input = preg_replace("/(\n)+/m", '\n', $input);
// Print formatted text
echo nl2br($input);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With