PHP REGEX查找和替换模式

时间:2019-12-29 06:29:16

标签: php regex preg-replace

试图构造一个正则表达式,以查找任何字符模式,后跟双引号

此正则表达式可以正确定位每次出现的情况

(\S"")

给出以下示例

$string='"WEINSTEIN","ANTONIA \"TOBY"","STILES","HOOPER \"PETER"","HENDERSON",';
$pattern = '(\S"")';
$replacement = '\\""';
$result=preg_replace($pattern, $replacement, $string);

我的结果竟然是

"WEINSTEIN","ANTONIA \"TOB\"","STILES","HOOPER \"PETE\"","HENDERSON"

但是我正在寻找

"WEINSTEIN","ANTONIA \"TOBY\"","STILES","HOOPER \"PETER\"","HENDERSON"

我知道替换项是删除/替换整个匹配项,但是如何删除除第一个字母之外的所有字母,而不是完全替换呢?

1 个答案:

答案 0 :(得分:1)

您可以将模式更改为使用正向后视,以免捕获非空格字符:

$string='"WEINSTEIN","ANTONIA \"TOBY"","STILES","HOOPER \"PETER"","HENDERSON",';
$pattern = '/(?<=\S)""/';
$replacement = '\\""';
$result=preg_replace($pattern, $replacement, $string);
echo $result;

输出

"WEINSTEIN","ANTONIA \"TOBY\"","STILES","HOOPER \"PETER\"","HENDERSON",

Demo on 3v4l.org