12

So when I run json_encode, it grabs the \r\n from MySQL aswell. I have tried rewriting strings in the database to no avail. I have tried changing the encoding in MySQL from the default latin1_swedish_ci to ascii_bin and utf8_bin. I have done tons of str_replace and chr(10), chr(13) stuff. I don't know what else to say or do so I'm gonna just leave this here....

$json = json_encode($new);
if(isset($_GET['pretty'])) {
echo str_replace("\/", "/", jsonReadable(parse($json)));
} else {
$json = str_replace("\/", "/", $json);
echo parse($json);
}

The jsonReadable function is from here and the parse function is from here. The str_replaces that are already in there are because I am getting weird formatted html tags like </h1>. Finally, $new is an array which is crafted above. Full code upon request.

Help me StackOverflow. You're my only hope

3
  • Have you read the JSON specification yet? json.org Commented Nov 19, 2010 at 23:06
  • Yeah I have worked with JSON for a long time, thing is that the output of this script is being picked up by flash for a CMS & flash no-likey the \r\n stuff. It just inserts new lines which we don't want. We want <br />. And yes, I tried nl2br, no luck. Commented Nov 19, 2010 at 23:10
  • So then someone decided to not implement JSON properly in the Flash. Lovely. Commented Nov 19, 2010 at 23:53

3 Answers 3

12

Does the string contain "\r\n" (as in 0x0D 0x0A) or the literal string '\r\n'? If it's the former, this should remove any newlines.

$json = preg_replace("!\r?\n!", "", $json);

Optionally, replace the second parameter "" with "<br />" if you'd like to replace the newlines with a br tag. For the latter case, try the following:

$json = preg_replace('!\\r?\\n!', "", $json);
Sign up to request clarification or add additional context in comments.

1 Comment

This didn't work, they are still there. I think maybe it has something to do with MySQL :/
7

Don't replace it in the JSON, replace it in the source before you encode it.

Comments

2

I had a similar issue, i used:

$p_num = trim($this->recp);
$p_num = str_replace("\n", "", $p_num);
$p_num = str_replace("\r", ",", $p_num);
$p_num = str_replace("\n",',', $p_num);
$p_num = rtrim($p_num, "\x00..\x1F");

Not sure if this will help with your requirements.

1 Comment

This also didn't work, again, I think this might be a MySQL issue. Thank you for the attempt though! high-five

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.