PHP json_解码json_编码的字符串
我真的不明白以下PHP json_解码json_编码的字符串,php,regex,Php,Regex,我真的不明白以下 // array to encode $a = ['regex' => '\/\+\/']; // decoding an encoded array works print_r(json_decode(json_encode($a), true)); // encoded array echo json_encode($a); // trying to decode the before encoded string doesn't work print_r(js
// array to encode
$a = ['regex' => '\/\+\/'];
// decoding an encoded array works
print_r(json_decode(json_encode($a), true));
// encoded array
echo json_encode($a);
// trying to decode the before encoded string doesn't work
print_r(json_decode('{"regex":"\\\/\\+\\\/"}', true));
echo json_last_error_msg();
最后一条错误消息显示语法错误
。难道我不能轻松地解码一个简单的编码字符串吗
我知道问题出在反斜杠上,但我不想做任何魔术字符串替换或正则表达式来让解码工作。只是想了解哪里出了什么问题,对于这种情况,什么是最佳实践
我正在使用PHP版本5.5.9,由于这个答案,我发现了一些东西: 如果使用
var_export(json_encode($a)),而不是使用echo
输出的字符串代码>(),它给你{“regex”:“\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
print\r(json解码(“{”regex:“\\\/\\\\\+\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\代码>给出了预期的结果:
Array
(
[regex] => \/\+\/
)
没有错误。问题在于,在PHP代码字符串文本中使用反斜杠要遵守PHP的反斜杠转义规则。您还需要转义反斜杠,以便它们保留在PHP字符串中:
print_r(json_decode('{"regex":"\\\\\\/\\\\+\\\\\\/"}', true));
与之相比:
echo '{"regex":"\\\/\\+\\\/"}';
// {"regex":"\\/\+\\/"}
嗯。在同一个PHP版本中,我得到了<代码>无效的字符串序列错误。如果它是你所需要的,请考虑接受一个回答@