Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/228.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP中的哪个正则表达式可以处理内部双引号的反斜杠?_Php_Regex - Fatal编程技术网

PHP中的哪个正则表达式可以处理内部双引号的反斜杠?

PHP中的哪个正则表达式可以处理内部双引号的反斜杠?,php,regex,Php,Regex,可能重复: 我有这样的数据: "manager1": "Richard "Dick" Smith, MD, MBA", 但要使用JSON,它必须看起来像这样: "manager1": "Richard \"Dick\" Smith, MD, MBA", 注意:不同之处在于仅对Dick昵称的内部双引号使用反斜杠,而对字符串的其余部分不做任何更改 我在处理用逗号分隔的证书(MD、MBA)时遇到问题。如何在PHP中使用正则表达式实现这一点,同时只反斜杠内部双引号,同时保留字符串的其余部分?谢谢

可能重复:

我有这样的数据:

"manager1": "Richard "Dick" Smith, MD, MBA",
但要使用JSON,它必须看起来像这样:

"manager1": "Richard \"Dick\" Smith, MD, MBA",
注意:不同之处在于仅对Dick昵称的内部双引号使用反斜杠,而对字符串的其余部分不做任何更改

我在处理用逗号分隔的证书(MD、MBA)时遇到问题。如何在PHP中使用正则表达式实现这一点,同时只反斜杠内部双引号,同时保留字符串的其余部分?谢谢

这不是一个复制品
因为该例程无法处理凭据中的其他逗号

我建议你这样做:

//suppose your data is in the file named "data.txt". We read it in a variable

$fh = fopen("data.txt");
$res = '';
while (($line = fgets($fh)) !== false) {
   $txt = explode(': ', $line);
   $txt[1] = trim($txt[1], '",'); 
   //now $txt[1] holds the the data with internal quotes but without external quotes
   $txt[1] = preg_replace('@"@', '\"',  $txt[1]);
   //put leading and ending quotes back and join everything back together
   $txt[1] = '"'.$txt[1].'",';
   $res .= implode(': ', $txt);

}

fclose($fh);

//now echo the result with the all internal quotes escaped
echo $res;

我认为上面的内容应该适合您。

以下正则表达式模式:

 /^\s+"[a-z0-9_"]+": "([^"]*".*)",?$/mi

是为我做的。请参见

我认为您没有办法修复导致数据看起来像这样的问题,因此您现在需要修复症状?是的,Tim,我无法控制此数据的来源来修复问题。不幸的是,我必须想出一个解决方案来纠正这个可能的JSON数据。@Quentin,该代码无法处理这个示例必须处理的额外逗号。感谢您提供的代码$txt没有值,这使得PHP为分解行生成“PHP警告:explode()希望参数2是字符串,数组在…”中给出。对,它应该是$txt=explode(“:”,$line)。我已经更正了代码,还编辑了代码以处理更新的结束代码。我还向fopen添加了“r”来运行它。它在每行的最后一个双引号上做一个反斜杠。