Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/297.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP json_解码json_编码的字符串_Php_Regex - Fatal编程技术网

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版本中,我得到了<代码>无效的字符串序列错误。如果它是你所需要的,请考虑接受一个回答@