首页 > 解决方案 > 如果需要,正则表达式如何转义双引号

问题描述

我需要将所有大整数转换为响应 json 中的字符串。目前我的正则表达式看起来像这样

preg_replace(
            '/:\s*(-?\d{16,})/',
            ': "$1"',
            $content
        );

但是这种正则表达式的问题是,如果我的响应包含另一个 json 字符串,那么其中的 bigints 也会被包裹在字符串中,但不会转义。在这种情况下,有没有办法逃避附加的引号?或者也许用另一个正则表达式修复不正确的 json?

例子

{"example_bigint": 3330922503411457761} 

will be converted to

{"example_bigint": "3330922503411457761"} 

but

{"example_json" : "{\"example_bigint\": 3330922503411457761}"} 

will be converted to 

{"example_json" : "{\"example_bigint\": "3330922503411457761"}"} 

when expected output is

{"example_json" : "{\"example_bigint\": \"3330922503411457761\"}"} 

标签: phpregex

解决方案


json_decode 函数中有一个标志:

$myJson = json_decode($jsonString, flags: JSON_BIGINT_AS_STRING);

推荐阅读