Php Preg_替换字符串之间的字符

Php Preg_替换字符串之间的字符,php,regex,json,preg-replace,preg-match,Php,Regex,Json,Preg Replace,Preg Match,我正在尝试编写一种最有效的方法,从json提要中转义双引号(“),该提要在不正确的位置包含引号 即 {“计数”:“1”,“查询”:“www.mydomain.com/watchlive/type/livedvr/event/69167/%20%20sTyLe=X:eX/**/pReSsIoN(window.location=56237)%20”,“错误”:“500”} 上面有三个键-count、query和error。“query”中的值无效,因为额外的双引号表示无效的json 如果我使用\“转

我正在尝试编写一种最有效的方法,从json提要中转义双引号(“),该提要在不正确的位置包含引号

{“计数”:“1”,“查询”:“www.mydomain.com/watchlive/type/livedvr/event/69167/%20%20sTyLe=X:eX/**/pReSsIoN(window.location=56237)%20”,“错误”:“500”}

上面有三个键-count、query和error。“query”中的值无效,因为额外的双引号表示无效的json

如果我使用\“转义它,那么json是有效的,可以由PHP引擎解析,但是由于json可以有5000多组数据,我不能手动去更改有问题的行

我知道使用preg_match和str_replace的组合会起作用,但它的代码非常混乱且不可维护。我需要reg_ex在类似这样的事情中使用

$buffer='{“count”:“1”,“query”:“www.mydomain.com/watchlive/type/livedvr/event/69167/%20%20sTyLe=X:eX/**/pReSsIoN(window.location=56237)%20”,“错误”:“500”}”

preg_match('/(查询):)(.*)(“,“error)/”,$buffer,$match)

谢谢 提前

使用以下工具进行匹配和替换:


说明:

(?:                # Start non-capturing group
  "query"\s*:\s*"  # Match "query":" literally, with optional whitespace  
 |                 # OR
  (?<!\A)          # Make sure we are not at the beginning of the string
  \G               # Start at the end of last match
)                  # End non-capturing
[^"]*              # Go through non-" characters
\K                 # Remove everything to the left from the match
"                  # Match " (this will be the only thing matched and replaced)
(?=                # Start lookahead group
  .*?",            # Lazily match up until the ", (this is the end of the JSON value)
)                  # End lookahead group
(?:#启动非捕获组
“查询”\s*:\s*“#匹配”查询“:”按字面意思,带有可选空格
|#或

(?这很有魅力,非常感谢,特别是有了额外的信息,这有助于了解表达式中发生了什么:)很高兴我能帮忙,希望解释有帮助。
$buffer = preg_replace('/(?:"query"\s*:\s*"|(?<!\A)\G)[^"]*\K"(?=.*?",)/', '\"', $buffer);
var_dump($buffer);
(?:                # Start non-capturing group
  "query"\s*:\s*"  # Match "query":" literally, with optional whitespace  
 |                 # OR
  (?<!\A)          # Make sure we are not at the beginning of the string
  \G               # Start at the end of last match
)                  # End non-capturing
[^"]*              # Go through non-" characters
\K                 # Remove everything to the left from the match
"                  # Match " (this will be the only thing matched and replaced)
(?=                # Start lookahead group
  .*?",            # Lazily match up until the ", (this is the end of the JSON value)
)                  # End lookahead group