Log in

View Full Version : Resolved line breaks from textarea json_encode



ggalan
09-15-2011, 04:46 PM
i have a textarea input field and when you hit the return key json_encode will output the actual break, not interpret it as \n or <br> like this. this line breaks my code


{"data":[
{"index":3,"text":"blue
","img":"blue.jpg"},
{"index":2,"text":"green","img":"green.jpg"},
{"index":1,"text":"something","img":"yellow.jpg"}
]}

i would like it to output like this


{"data":[
{"index":3,"text":"blue\n","img":"blue.jpg"},
{"index":2,"text":"green","img":"green.jpg"},
{"index":1,"text":"something","img":"yellow.jpg"}
]}

heres a truncated section of my code


<form id="itmSubmit" method="POST">
<textarea id="entryItm" name="entryItm" cols="50" rows="1" wrap="off"></textarea><br/>
<input class="itmSubmit" type="submit" value="enter" />
</form>


$nTitle = $_POST['entryItm']; // get posted comment
$dataArr = array('index' => $num++, 'text' => $nTitle, 'img' => 'blank.jpg');
array_unshift($dataList['data'], $dataArr);
$dataTxt = json_encode($dataList);

is there a way to output the enter key hit as \n in the json output?

jscheuer1
09-15-2011, 05:20 PM
You could assign the value of the field using preg_replace() to an interim variable, and then use that variable in place of its value or it's value's place in the array.

ggalan
09-15-2011, 05:23 PM
tried this


$nTitle = preg_replace("\n", "<br/>", $nTitle);

but now i get a message


Warning: preg_replace() [function.preg-replace]: Empty regular expression

ggalan
09-15-2011, 05:28 PM
got it


$nTitle = trim( preg_replace( '/\s+/', '<br/>', $nTitle ) );

jscheuer1
09-15-2011, 06:27 PM
Using \s is any whitespace between words including tabs and spaces. The + after it would eliminate all but two or more of those in a row, but not all of those occurrences are line breaks, and not all line breaks qualify for that, and you said you wanted \n not <br/> though that might be preferable in this case if workable.

Instead of \s, you might want \n, but the trouble with that is that the kind of line break depends upon the OS of the browser and upon the browser. It can be \n or \r or \r\n

Perhaps:


$nTitle = trim( preg_replace( '/(\r\n)|\n|\r/', '<br/>', $nTitle ) );

or for replacement with \n:


$nTitle = trim( preg_replace( '/(\r\n)|\n|\r/', '\\n', $nTitle ) );

ggalan
09-15-2011, 07:33 PM
regex always gets confusing : (