[英]SKIP-FAIL regex with multiple patterns to ignore in one PCRE regex
I'm trying to replace one string with another but only if it's out of double or single quotes. 我试图将一个字符串替换为另一个字符串,但前提是该字符串必须用双引号或单引号引起来。 I can do it for doubles, but I have problems to include singles as well.
我可以做双打,但是也有单打的问题。
I use preg_repalce with array because I also have other rules to apply to the string. 我将preg_repalce与array一起使用,因为我还有其他适用于字符串的规则。
$text = <<<DATA
I love php
"I love php"
'I love php'
"I" love 'php'
DATA;
$text = preg_replace(
[
'/"[^"]*"(*SKIP)(*FAIL)|\blove\b/i'
],
[
'hate'
],
$text
);
echo $text;
and the output is 输出是
I hate php -> OK
"I love php" -> OK
'I hate php' -> NOT OK
"I" hate 'php' -> OK
my problem is the single quotes 我的问题是单引号
As an alternative, you may also a capture group to capture single or double quote and a back-reference to match the same quote: 或者,您也可以使用捕获组来捕获单引号或双引号,并使用反向引用来匹配相同的引号:
$re = '/([\'"]).*?\1(*SKIP)(*F)|\blove\b/';
PHP Code: PHP代码:
$re = '/([\'"]).*?\1(*SKIP)(*F)|\blove\b/';
$text = preg_replace($re, 'hate', $text);
You need to group the alternatives you want to SKIP-FAIL and escape single quotes as you are using a single-quoted string literal: 您需要对要跳过的分组进行分组 ,并使用单引号的字符串文字时对单引号进行转义:
'/(?:\'[^\']*\'|"[^"]*")(*SKIP)(*FAIL)|\blove\b/i'
^^^ ^ ^
See the regex demo . 参见regex演示 。
Now, (*SKIP)(*FAIL)
will apply to both the alternatives, \\'[^\\']*\\'
and "[^"]*"
. 现在,
(*SKIP)(*FAIL)
将适用于\\'[^\\']*\\'
和"[^"]*"
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.