替换所有引号但保留转义字符

Replace all quote marks but leave escaped characters

我正在尝试从字符串中删除所有引号字符,但不删除那些被转义的字符。

示例:

#TEST string "quoted part\" which escapes" other "quoted string"

结果应该是:

#TEST string quoted part\" which escapes other quoted string

我尝试使用

实现此目的
$string = '#TEST string "quoted part\" which escapes" other "quoted string"'
preg_replace("/(?>=\)([\"])/","", $string);

但似乎找不到匹配模式。

关于其他方法的任何帮助或提示

(*SKIP)(*FAIL)的一个很好的例子:

\['"](*SKIP)(*FAIL)|["']

将其替换为空字符串即可。参见 a demo on regex101.com


PHP 中,这将是(您也需要转义反斜杠):

<?php

$string = <<<DATA
#TEST string "quoted part\" witch escape" other "quoted string"
DATA;

$regex = '~\\[\'"](*SKIP)(*FAIL)|["\']~';

$string = preg_replace($regex, '', $string);
echo $string;

?>

a demo on ideone.com

可能是这个

$str = '#TEST string "quoted part\" witch escape" other "quoted string"';

echo preg_replace("#([^\\])\"#", "", $str);

虽然 (*SKIP)(*F) 总而言之是一项很好的技术,但在这种情况下,您似乎可以使用纯粹的负面回溯,其中可能不会出现其他转义实体,但会转义引号:

preg_replace("/(?<!\\)[\"']/","", $string);

参见regex demo

在这里,正则表达式匹配...

  • (?<!\\) - 字符串中没有紧跟文字反斜杠的位置(请注意,在 PHP 字符串文字中,您需要两个反斜杠来定义文字反斜杠,并匹配带有正则表达式模式的文字反斜杠,字符串文字中的文字反斜杠必须加倍,因为反斜杠是特殊的正则表达式元字符)
  • [\"'] - 双引号或单引号。

PHP demo:

$str = '#TEST string "quoted part\" witch escape" other "quoted string"';
$res = preg_replace('/(?<!\\)[\'"]/', '', $str);
echo $res;
// => #TEST string quoted part\" witch escape other quoted string

如果输入中的反斜杠也可能被转义,您需要确保不匹配两个 \ 之后的 " (因为在那种情况下," 不会转义):

preg_replace("/(?<!\\)((?:\\{2})*)[\"']/",'', $string);

((?:\\{2})*) 部分将在 "' 之前捕获成对的 \s,并在 反向引用的帮助下将它们放回去。