Robert
Robert

Reputation: 138

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

Upvotes: 0

Views: 355

Answers (2)

anubhava
anubhava

Reputation: 785571

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

Upvotes: 4

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627083

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 "[^"]*".

Upvotes: 2

Related Questions