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

问题描述 投票:1回答:3

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

例:

#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);

但似乎无法找到匹配模式。

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

php regex preg-replace
3个回答
2
投票

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

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

用空字符串替换它,你没事。见a demo on regex101.com


In PHP this would be (you need to escape the backslash as well):
<?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


2
投票

虽然(*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})*)[\"']/",'$1', $string);

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


1
投票

可能是这个

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

echo preg_replace("#([^\\\])\"#", "$1", $str);
© www.soinside.com 2019 - 2024. All rights reserved.