Match and replace using this expression:
(?:"query"\s*:\s*"|(?<!\A)\G)[^"]*\K"(?=.*?",)
\"
In PHP, this would use preg_replace()
:
$buffer = preg_replace('/(?:"query"\s*:\s*"|(?<!\A)\G)[^"]*\K"(?=.*?",)/', '\"', $buffer);
var_dump($buffer);
Explanation:
(?: # 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