我有这个字符串可用于 json_decode()和 PHP 5.6 ,但不适用于 PHP 7.2 ?
$json = '
{
"text": "Hi {{fname}}
Welcome to our customer support.
Please select language to proceed",
"buttons": [
{
"text": "English",
"value": "language_english",
"type": "postback"
},
{
"text": "Germany",
"value": "language_germany",
"type": "postback"
}
]
}';
我尝试过这样替换空白和换行符
$json = preg_replace("/\n/m", '\n', $json);
$what = "\\x00-\\x19"; // all whitespace characters except space itself
$json = trim(preg_replace( "/[".$what."]+/" , '' , $json));
哪个结果像这样的字符串
\n{\n "text": "Hi {{fname}} \n Welcome to our customer support. \n Please select language to proceed",\n "buttons": [\n {\n "text": "English",\n "value": "language_english",\n "type": "postback"\n },\n {\n "text": "Germany",\n "value": "language_germany",\n "type": "postback"\n }\n ]\n}
请注意,双引号之间和双引号之间的\n
使其成为无效的json,因此在这种情况下json_decode无法使用。
有人知道实现这一目标的方法吗?
谢谢。
答案 0 :(得分:0)
{
"text": "Hi {{fname}} \n Welcome to our customer support. \n Please select language to proceed",
"buttons": [{
"text": "English",
"value": "language_english",
"type": "postback"
},
{
"text": "Germany",
"value": "language_germany",
"type": "postback"
}
]
}
这是有效的json。我添加了换行符,以便在浏览器中打印消息时可以使用它们。
如果有疑问,可以使用这个不错的tool来验证json。
根据评论反馈编辑我的答案。
首先,正确的步骤是弄清楚为什么数据库中的json损坏。如果它不在您身上,而您必须在php中修复它,则解决方案可能是这样的:
<?php
echo '<pre>';
$data = '
{
"text": "Hi {{fname}}
Welcome to our customer support.
Please select language to proceed",
"buttons": [
{
"text": "English",
"value": "language_english",
"type": "postback"
},
{
"text": "Germany",
"value": "language_germany",
"type": "postback"
}
]
}';
if (strstr($data, "\n")) {
$data = trim(preg_replace('/\s\s+/', ' ', $data));
}
echo $data;
以上代码将捕获您的文本字段的换行符,并将其替换为 DOUBLE 空格。然后您将获得一个有效的json,如:
{
"text": "Hi {{fname}} Welcome to our customer support. Please select language to proceed",
"buttons": [
{
"text": "English",
"value": "language_english",
"type": "postback"
},
{
"text": "Germany",
"value": "language_germany",
"type": "postback"
}
]
}
如果需要换行符,您可以做的是对json进行解码(就像您想要的那样,并用换行符替换text
字段中的双倍空格