Home >Backend Development >PHP Tutorial >json_decode解析backslash时报错

json_decode解析backslash时报错

WBOY
WBOYOriginal
2016-06-06 20:41:301326browse

<code>$array = array(
    'code_pattern' => '\d{6}'
);
//ok
print_r(json_decode(json_encode($array),true));
//error
print_r(json_decode('{"code_pattern":"\\d{6}"}',true));
</code>

这个问题怎么解决?

补充:

<code>$array = array(
    'code_pattern' => '\d{6}'
);

$arr_str = json_encode($array);
echo $arr_str . "\n";
//ok
print_r(json_decode($arr_str,true));
//error
$arr_dec = json_decode('{"code_pattern":"\\d{6}"}',true);
var_dump($arr_dec);
</code>

结果:

<code>.{"code_pattern":"\\d{6}"}
Array
(
    [code_pattern] => \d{6}
)
NULL


Time: 102 ms, Memory: 7.25Mb
</code>

回复内容:

<code>$array = array(
    'code_pattern' => '\d{6}'
);
//ok
print_r(json_decode(json_encode($array),true));
//error
print_r(json_decode('{"code_pattern":"\\d{6}"}',true));
</code>

这个问题怎么解决?

补充:

<code>$array = array(
    'code_pattern' => '\d{6}'
);

$arr_str = json_encode($array);
echo $arr_str . "\n";
//ok
print_r(json_decode($arr_str,true));
//error
$arr_dec = json_decode('{"code_pattern":"\\d{6}"}',true);
var_dump($arr_dec);
</code>

结果:

<code>.{"code_pattern":"\\d{6}"}
Array
(
    [code_pattern] => \d{6}
)
NULL


Time: 102 ms, Memory: 7.25Mb
</code>

你输出一下json_encode($array)的值就知道为什么了。

测试了一下,json_encode($arry)会输出{"code_pattern":"\\d{6}"},它将\进行了转义。但是你需要使用json_decode('{"code_pattern":"\\\\d{6}"}')才能得到想要的结果\d{6}

题外话:SF怎么不支持markdown删除线的语法呢?我在编辑答案的时候是可以看到效果的,展示出来就没有了。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn