简体   繁体   中英

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.

$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/';

RegEx Demo

PHP Code:

$re = '/([\'"]).*?\1(*SKIP)(*F)|\blove\b/';
$text = preg_replace($re, 'hate', $text);

Code Demo

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 .

Now, (*SKIP)(*FAIL) will apply to both the alternatives, \\'[^\\']*\\' and "[^"]*" .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM