Adrien Hingert
Adrien Hingert

Reputation: 1516

PHP replace newlines stored in MySQL DB

I have a MySQL table with 2 columns:

  1. text: stores a multi-line text which could have line breaks as \n, \r, \r\n.... The text is inserted via a webform and could have been inserted by any browser on any OS.

  2. line_break: represents what type of line break this particular text will use (could be \n, <br>, <br />, ...). This is also inserted via a webform by a user.

In PHP I then do the replacement:

$text = preg_replace ("/(\r\n|\r|\n)/", $row['line_break'], $row['text']);

Interestingly, if the line break is stored in the DB as \n I will actually show \n instead of the newline. On the other hand, the following regexp will work correctly:

$text = preg_replace ("/(\r\n|\r|\n)/", "\n", $row['text']);

How do I need to store the newline in the DB for it to "work" correctly?

Upvotes: 3

Views: 1682

Answers (1)

GolezTrol
GolezTrol

Reputation: 116100

In php, "\n" is a special notation for writing that special character that means 'line break'. But if you store the actual text \n in your database, you have just that text, and not the line break character. You have what you get when you write '\n' or "\\n" in PHP. Make sure you store the actual line break character in your database and not the literal \n text.

Upvotes: 4

Related Questions