【发布时间】:2018-11-27 08:26:40
【问题描述】:
我有这个字符串可以在 PHP 5.6 中使用 json_decode() 但不适用于 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在这种情况下不起作用。
有谁知道实现这一目标的方法吗?
谢谢。
【问题讨论】:
-
你为什么首先使用损坏的 JSON?
-
这不是一个有效的 json。 json_decode 不能解码不是 json 但看起来像的东西。
-
它适用于 no 版本的 PHP:3v4l.org/Wq5L5