php 运行 json_encode 后替换 \r\n(换行符)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4230170/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 12:20:55  来源:igfitidea点击:

Replacing \r\n (newline characters) after running json_encode

phpmysqlstr-replacejson

提问by Robbie Trencheny

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_encode 时,它​​也会从 MySQL 中获取 \r\n。我试过重写数据库中的字符串无济于事。我尝试将 MySQL 中的编码从默认的 latin1_swedish_ci 更改为 ascii_bin 和 utf8_bin。我已经做了大量的 str_replace 和 chr(10), chr(13) 的东西。我不知道还能说什么或做什么,所以我要把这个留在这里......

$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 hereand 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.

jsonReadable 函数来自这里,解析函数来自这里。已经在那里的 str_replaces 是因为我得到了像 </h1> 这样奇怪的格式化 html 标签。最后,$new 是一个上面精心制作的数组。应要求提供完整代码。

Help me StackOverflow. You're my only hope

帮助我 StackOverflow。你是我唯一的希望

采纳答案by Frankie

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.

字符串是否包含“\r\n”(如 0x0D 0x0A)或文字字符串 '\r\n'?如果是前者,这应该删除任何换行符。

$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:

或者,如果您想用 br 标签替换换行符,请将第二个参数“”替换为“<br />”。对于后一种情况,请尝试以下操作:

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

回答by Ignacio Vazquez-Abrams

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

不要在 JSON 中替换它,在编码之前在源中替换它。

回答by Kyle Hudson

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.

不确定这是否有助于满足您的要求。