6

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>.

Nikola K.
  • 7,093
  • 13
  • 31
  • 39
bodesam
  • 529
  • 4
  • 9
  • 24
  • possible duplicate of [How to remove line breaks (no characters!) from the string?](http://stackoverflow.com/questions/10757671/how-to-remove-line-breaks-no-characters-from-the-string) – kenorb Mar 03 '15 at 00:27

2 Answers2

5

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.

MrWhite
  • 43,179
  • 8
  • 60
  • 84
  • 1
    You are correct, I found out, I had to convert back the output to new lines. I used the following code and it worked: $output = preg_replace("/(\n)+/m", '
    ', $output);
    – bodesam Jul 10 '12 at 12:59
3

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);
Florent
  • 12,310
  • 10
  • 49
  • 58
  • 1
    Thanks, the issue with nl2br is that it doesn't work if the input is copied and pasted into the text area instead of typing directly and hitting the enter key. – bodesam Jul 10 '12 at 12:53
  • I think you need to clear CRLF. Please take a look at my edit. – Florent Jul 10 '12 at 12:59