Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving line breaks with preg_replace

Tags:

php

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

like image 343
bodesam Avatar asked Jul 10 '12 12:07

bodesam


2 Answers

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.

like image 69
MrWhite Avatar answered Oct 16 '22 18:10

MrWhite


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);
like image 39
Florent Avatar answered Oct 16 '22 19:10

Florent