Saving line aborts with preg_replace

I have this code to save line breaks in the text area entered into the database:

$input = preg_replace("/(\n)+/m", '\n', $input); 

When examining input in a database, line breaks are actually saved.
But the problem is when I want to repeat this, line breaks do not appear on the output, how to save line breaks in the input, and also drop them out. I do not want to use <pre></pre> .

+4
source share
2 answers

You replace the actual sequence of newline strings in $input literal character sequence \n (backslash + n) - not a new line. They must be converted back to new lines when reading from the database. Although I suspect that you intend to store these actual strings in the database and use a double-quoted string instead ...

 $input = preg_replace('/(\n)+/m', "\n", $input); 

Notice that I replaced the first line delimiters with single quotes and the second double-quoted string. \n is a special sequence in a regular expression to indicate a new line (ASCII 10), but it is also a character escape code in PHP indicating the same thing: conflicts can sometimes occur.

+3
source

I think PHP has a solution:

nl2br - Insert HTML line breaks before all newlines in a line

Edit: You may need to replace CR / LF for it to work correctly.

 // 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); 
+1
source

All Articles