首页 > json_decode解析backslash时报错

json_decode解析backslash时报错

$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));

这个问题怎么解决?

补充:

$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_pattern":"\\d{6}"}
Array
(
    [code_pattern] => \d{6}
)
NULL


Time: 102 ms, Memory: 7.25Mb

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

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

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

【热门文章】
【热门文章】