我正在尝试用短语中的一些特殊字符替换空格。但我只是根据条件匹配空间。检查以下示例以了解!
我不想将空格与尾随和前导特殊字符串相匹配,例如
AND, OR, NOT, -
我的示例字符串
apple google AND bing NOT yahoo
在上面的示例中,我只想匹配 apple google 之间的空格。所以写下面的代码。
$q = 'apple google AND bing NOT yahoo';
$pattern1 = '/(?<!AND|NOT|OR)[ ](?!-|AND|NOT|OR)/';
$replacement1 = ' ## ';
echo $qs = preg_replace($pattern1, $replacement1, $q,-1);
这是输出
apple ## google AND bing NOT yahoo
我的问题 现在,带引号的字符串。我想忽略引号之间的空格。
"apple google" AND bing NOT yahoo => should be 0 match
那么如何编写表达式来做到这一点呢?
最佳答案
你可以使用这个正则表达式:
$s = '"apple google" AND bing NOT yahoo "word a-b"';
$r = preg_replace('/(?=(([^"]*"){2})*[^"]*$)(?<!AND|NOT|OR) +(?!-|AND|NOT|OR)/i',
' ## ', $s);
echo "$r"; // "apple google" AND bing NOT yahoo ## "word a-b"
这假设输入中的引号是平衡的,因为它通过计算前瞻中后面的引号数量来检测引号内的文本。
关于php - 正则表达式忽略双引号内的匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22963641/