使用php preg_replace解析出JSON字符串中的目标双引号


Using php preg_replace to parse out target double quotes in JSON string

我一直在绞尽脑汁,想不出一个regexp来完成以下任务:

输入字符串(这是JSON数据被许多其他JSON包围):

$string=..."natural_order":"12"...

其中12也可以是小数,如"1.2",也可以是更大的数字,如1288或1.288。

所需的字符串:

..."natural_order":12...

使用php preg_replace,到目前为止,我已经得到:

preg_replace('/[^natural_order:]+"/', '', $string);

但只返回:

"12"

任何想法都非常感谢!

我的建议是:

$array = json_decode($string, true);
array_walk_recursive($array, function (&$value, $key) {
    if ($key == 'natural_order') {
        $value = strpos($value, '.') ? (float)$value : (int)$value;
    }
});
$string = json_encode($array);

我可以想到两个解决方案。第一种方法,我就不写了,是使用json_decode解码JSON,通过将其解析为整型来纠正值,然后重新编码字符串。

第二个是继续你的道路。然而,JSON是一个相当复杂的字符串,不能仅使用正则表达式可靠地解析。如果您确信模式"natural_order":"value"不会出现在其他地方,您可以尝试这样做:

$result = preg_replace('/"natural_order"'s*':'s*"([-+]?[0-9]*'.?[0-9]+)"/', '"natural_order":$1', $string);

这应该匹配任何封装的键,后面跟着一个冒号,后面跟着一个封装的有效浮点数。如果冒号周围有空格,也可以使用转义