I have:
$txt = ':D :D ":D" :D:D:D:D';
I want to preg_replace
all :D
to ^
and if ":D"
then not replace.
===> output: '^ ^ ":D" ^^^^';
(*SKIP)(*F) Magic
$replaced = preg_replace('~"[^"]+"(*SKIP)(*F)|:D~', '^', $yourstring);
In the demo, see the substitutions in the bottom pane.
This problem is a classic case of the technique explained in this question to "regex-match a pattern, excluding..."
The left side of the alternation |
matches complete "quotes"
then deliberately fails, after which the engine skips to the next position in the string. So the quotes are neutralized. The right side matches :D
, and we know they are the right ones because they were not matched by the expression on the left.
Reference