PHP json_decode一个json_encoded字符串

时间:2015-09-14 15:10:22

标签: 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(json_decode('{"regex":"\\\/\\+\\\/"}', true));
echo json_last_error_msg();

最后一条错误消息显示Syntax error。难道我不能轻松解码一个简单的编码字符串吗?

我知道问题出现在反斜杠中,但我不想做任何魔术字符串替换或正则表达式以使解码工作。只是想了解哪里出了什么问题,哪种情况最适合这种情况?

我使用的是PHP 5.5.9版本

2 个答案:

答案 0 :(得分:4)

Found something thanks to that answer : https://stackoverflow.com/a/10929508/1685538

If instead of taking the string outputted by echo, you use var_export(json_encode($a)); (documentation), it gives you {"regex":"\\\\\\/\\\\+\\\\\\/"}

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

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

with no errors.

答案 1 :(得分:1)

The problem is that using backslashes in PHP code string literals is subject to PHP's backslash escaping rules. You need to additionally escape the backslashes so they are preserved inside the PHP string:

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

Contrast with:

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