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

时间:2017-03-26 17:40:09

标签: php regex preg-replace

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

示例:

  

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

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

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

3 个答案:

答案 0 :(得分:2)

(*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

答案 1 :(得分: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})*)部分将在\"之前捕获已配对的',并在$1反向引用的帮助下将其重新放回。

答案 2 :(得分:1)

可能是这个

git branch -a