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.
The best way is to use json_encode()
from the start. It fully escapes everything for output to Javascript.