简体   繁体   English

PHP json_decode一个json_encoded字符串

[英]PHP json_decode a json_encoded string

I don't really get the following... 我真的没有以下内容...

// 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();

The last error message says Syntax error . 最后一条错误消息显示Syntax error Shouldn't I be able to easily decode a simple encoded string? 我不应该能够轻松解码一个简单的编码字符串吗?

I know that the problem is in the backslashes but I won't want to do any magic string replacement or regex to get the decoding working. 我知道问题出在反斜杠,但我不想进行任何魔术字符串替换或正则表达式来使解码正常工作。 Just want to understand where goes what wrong and what's a best practice for this kind of situations? 只想了解哪里出了问题,在这种情况下最好的做法是什么?

I'm using PHP version 5.5.9 我正在使用PHP版本5.5.9

Found something thanks to that answer : https://stackoverflow.com/a/10929508/1685538 找到了感谢的答案: https : //stackoverflow.com/a/10929508/1685538

If instead of taking the string outputted by echo , you use var_export(json_encode($a)); 如果不是使用echo输出的字符串,则使用var_export(json_encode($a)); ( documentation ), it gives you {"regex":"\\\\\\\\\\\\/\\\\\\\\+\\\\\\\\\\\\/"} 文档 ),它会为您提供{"regex":"\\\\\\\\\\\\/\\\\\\\\+\\\\\\\\\\\\/"}

print_r(json_decode('{"regex":"\\\\\\\\\\\\/\\\\\\\\+\\\\\\\\\\\\/"}', true)); gives the expected result : 给出预期的结果:

Array
(
    [regex] => \/\+\/
)

with no errors. 没有错误。

The problem is that using backslashes in PHP code string literals is subject to PHP's backslash escaping rules. 问题在于,在PHP代码字符串文字中使用反斜杠必须遵守PHP的反斜杠转义规则。 You need to additionally escape the backslashes so they are preserved inside the PHP string: 您还需要转义反斜杠,以便将其保留在PHP字符串中:

print_r(json_decode('{"regex":"\\\\\\/\\\\+\\\\\\/"}', true));

Contrast with: 与:

echo '{"regex":"\\\/\\+\\\/"}'; 
//    {"regex":"\\/\+\\/"}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM