2

I have a dynamically generated array from a database. Basically it's an array of objects which PHP prints out to the page in the section.

The final output is somrthing like: var arPersons=[{'name':'aaa',description:'2-3 lines text in 300px wide div'},{etc}];

Now there seems to be a problem with this array when newline caracters (\n) or carriage return characters (\r) appear in the description text as that is written from a CMS.

How can I solve this? What I currently do is str_replace(array("\r\n","\r","\n"),"",$description);, where $description is changed for each element in the loop.

I am unsure this is the best way. Is there a way I can tell the JS code not to mess up when there are \n and \r characters somehow? Should it still be done in PHP rather than JS?

EDIT: By mess up I mean any code after that array stops being executed. If I remove description entirely or just the \n and \r characters it will work (in both cases).

Thank you.

Francisc
  • 77,430
  • 63
  • 180
  • 276
  • 1
    What exactly do you mean, "mess up"? What goes wrong? There's nothing inherently illegal or improper about newline or carriage return characters. – Pointy Dec 21 '10 at 19:16
  • It breaks any JS code after that part. if I remove the new line characters it works. I am also using jQuery on the page if that makes any difference. – Francisc Dec 21 '10 at 19:20

2 Answers2

6

The best way is to use json_encode() from the start. It fully escapes everything for output to Javascript.

http://php.net/json-encode

Jonah
  • 9,991
  • 5
  • 45
  • 79
  • Hmm, clever. I hope it doesn't affect HTML in the description property as it need it to have HTML. I'll give it a try and comeback. Thanks – Francisc Dec 21 '10 at 19:21
  • 1
    @Francisc no, it won't break the HTML. All it does is provide quoting as necessary to preserve JSON syntax, so HTML markup will be completely ignored. – Pointy Dec 21 '10 at 20:37
1

PHP has a nl2br() function that takes newlines in a string and turns them into <br />s. You could run your string through that if you are wanting to keep the formatting. The sub-par docs for nl2br are here

Madison Williams
  • 350
  • 1
  • 4
  • 11