tags:

views:

489

answers:

2

Hi, "replace newline" seems to be a question asked here and there like hundred times already. But however, i haven't found any working solution for myself yet.

I have a textarea that i use to save data into DB. Then using AJAX I want to get data from the DB in the backend that is in TEXT field and to pass it to frontend using JSON. But pasing JSON returns an error, as new lines from DB are not valid JSON syntax, I guess i should use \n instead...

But how do i replace newlinew from DB with \n?

I've tried this

$t = str_replace('<br />', '\n', nl2br($t));

and this

$t = preg_replace("/\r\n|\n\r|\r|\n/", "\n", $t);

and using CHAR(13) and CHAR(10), and still I get an error

the new line in textarea is equivalent to, i guess

$t = 'text with a 
newline';

it gives the same error. And in notepad i clearly see that it is crlf

A: 

Prfff... >_< silly me

I've lost another slash before replacing with \n

$t = preg_replace("/\r\n|\n\r|\r|\n/", "\\n", $t);
dr3w
A: 

You need to escape all the characters that have a special meaning in JSON, not only line feeds. And you also need to convert to UTF-8.

There's no need to reinvent the wheel, json_encode() can do everything for you.

Álvaro G. Vicario
Yeah, i've googled this one already, just wanted to update. it is really useful. I used to form json in completely other way before
dr3w