为什么preg_replace不会在引用后删除空格

时间:2016-01-19 14:48:25

标签: php regex preg-replace php-5.5

鉴于代码:

$SearchWords=['\'"','GOLF','FACILITIES','IN','CANADA','\'"'];

$s[1] = 'SUB2,DETRAN=("';
$s[1] .= implode(' ', array_filter($SearchWords));
$s[1] .= '"*) OR A=((';
//remove space after an opening quote mark
$s[1] = preg_replace("/('['\"])[ ](\S.*)([ ]\1)/U", "$1$2$3", $s[1]);
//remove space before closing quote mark
$s[1] = preg_replace("/('['\"])(\S.*)[ ](\1)/U", "$1$2$3", $s[1]);

结果应该是SUB2,DETRAN=("'"GOLF FACILITIES IN CANADA'""*) OR A=((而不是SUB2,DETRAN=("'" GOLF FACILITIES IN CANADA '""*) OR A=(((注意在GOLF之前和加拿大之后空间仍然存在)。谁能看到我做错了什么?我尝试过在字符类中使用和不使用空格。

PHP版本是5.5.9-1ubuntu4.14

1 个答案:

答案 0 :(得分:0)

这是因为您在双引号中使用模式并使用单个转义\1。用双引号时需要\\1

使用:

$s[1] = preg_replace("/('['\"]) (\S.*)( \\1)/U", "$1$2$3", $s[1]);
$s[1] = preg_replace("/('['\"])(\S.*) (\\1)/U", "$1$2$3", $s[1]);

echo $s[1];
//=> SUB2,DETRAN=("'"GOLF FACILITIES IN CANADA'""*) OR A=((