0

I a trying to add a line break to a text area at run time (\n) but instead of displaying as a line break the text area physically puts in \n. I have read various topics about this Link 1 and link 2 without any success. It could be down to the way the data is updated within the text area but that shouldn't matter. My data is brought in through json from a php file and displayed through jQuery

Example of json response:

{"error":"2","err_msg":"","data":"<p class=\"left\">Aligned left text<\/p><br>Sub text <br>"}

The text in the text area should then display:

[left]Aligned left text[/left]
Sub text

But on my page I get

[left]Aligned left text[/left]\nSub text

I have php function to convert relevent html tags to what I want them but for some reason line breaks don't work

$string = preg_replace_callback('(\<p class="left"\>(.*?)\</p\>)is', function($matches){
   $txt = $matches[1];
   return '[left]'.$txt.'[/left]\n';
}, $string);

$string = str_replace('<br>','\n',$string);

die(json_encode(array('error' => '2', 'err_msg' => '', 'data' => $string)));

There is a lot more formatting and different tags but its only the line break that doesn't work.

This change should be display in a text area

$('#edit').val(json.data)
<textarea id="edit" ></textarea>
Community
  • 1
  • 1
Paul Ledger
  • 1,125
  • 4
  • 21
  • 46

2 Answers2

3

Try using the HTML entities for line feed &#10; and carriage return &#13;.

BT643
  • 3,495
  • 5
  • 34
  • 55
2

Don't use string literals encapsulated with apostrophes, try:

$string = str_replace("<br>", "\n", $string)

There is a significant difference between 'this string' and "this string" in PHP; using apostrophes to encapsulate your string in PHP will treat \n literally as \n rather than chr(10).

CD001
  • 8,332
  • 3
  • 24
  • 28