正则表达式用preg_replace转义双引号内的双引号

vin*_*nux 4 php

我整天试图逃避双引号内的所有双引号(是的,疯狂的),我终于放弃了.我有这样的数据:

{ "test": "testing with "data" like this", "subject": "trying the "special" chars" }
Run Code Online (Sandbox Code Playgroud)

我一直在努力的preg_replace每一个"\"里面是这样的/"(.*)+, "/,这意味着双引号内的一切,跟一个逗号和空间.

我需要一种方法来解决这个问题:

{ "test": "testing with "data" like this", "subject": "trying the "special" chars" }
Run Code Online (Sandbox Code Playgroud)

进入:

{ "test": "testing with \"data\" like this", "subject": "trying the \"special\" chars" }
Run Code Online (Sandbox Code Playgroud)

使用preg_replace.

Aus*_*ust 10

看着你的正则表达式,我建议阅读正则表达式的贪婪.如果您在第一个逗号的引号之间选择所有内容,则会遇到问题.返回将是第一件事,test": "testing with "data" like this这样的话,如果你更换了所有"\"你有test\": \"testing with \"data\" like this这显然不是你想要的.我建议使用这样的东西:

/"((?:.|\n)*?)"\s*[:,}]\s*/
Run Code Online (Sandbox Code Playgroud)

说明

  • "((?:.|\n)*?)" - 捕获两个引文之间的任何字符; 仍然具有该模式的最小量是真实的
  • \s* - 匹配0个或更多的空格字符
  • [:,}] - 匹配冒号,逗号或右括号字符
  • \s* - 匹配0个或更多的空格字符

使用这个正则表达式和你的数据,返回的第一件事是test.接下来的事情就是testing with "data" like this更换后你会有的testing with \"data\" like this.


UPDATE

$test = '{ "test": "testing with "data" like this", "subject": "trying the "special" chars" }';
$pattern = '/"((?:.|\n)*?)"\s*[:,}]\s*/';
preg_match_all($pattern, $test, $matches);
foreach($matches[1] as $match){
    $answers[] = str_replace('"','\\"',$match);
}
print_r($answers);
// Outputs
// Array ( [0] => test [1] => testing with \"data\" like this [2] => subject [3] => trying the \"special\" chars )
Run Code Online (Sandbox Code Playgroud)


更新2

我认为使用preg_match_all然后str_replace是解决问题的更好方法,因为正则表达式更加稳定.但如果你坚持使用preg_replace那么你可以使用这个代码:

$string = '{ "test": "testing with "data" like this", "subject": "trying the "special" chars" }';
$pattern = '/(?<!:|: )"(?=[^"]*?"(( [^:])|([,}])))/';
$string = preg_replace($pattern, '\\"', $string);
print_r($string);
//Outputs
//{ "test": "testing with \"data\" like this", "subject": "trying the \"special\" chars" }
Run Code Online (Sandbox Code Playgroud)

说明

  • (?<! - 开始消极的观察
  • :|: ) - 将冒号或冒号与空格匹配并结束后视
  • " - 匹配报价
  • (?= - 开始积极前瞻
  • [^"]*? - 匹配报价以外的任何内容; 仍然具有该模式的最小量是真实的
  • "(( [^:])|([,}])) - 匹配引号后跟空格和除结肠之外的任何内容或它匹配引号后跟逗号或右括号
  • ) - 结束前瞻

您可以在此处阅读有关正则表达式前瞻的更多信息.我认为这个正则表达式是混乱的,虽然从技术上来说它是有效的.我打算继续玩它让它变得更好但是我累了所以我现在要去睡觉了.此正则表达式允许您的数据更松散地输入.这些都可以,以及它们的任意组合:

{ "test" : "testing with "data" like this" , "subject" : "trying the "special" chars" }
{"test":"testing with "data" like this","subject":"trying the "special" chars"}
Run Code Online (Sandbox Code Playgroud)