Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace :D emoticons, except inside ":D"

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" ^^^^';
like image 661
dqnhust Avatar asked Dec 05 '25 03:12

dqnhust


1 Answers

(*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

  • How to match (or replace) a pattern except in situations s1, s2, s3...
  • Article about matching a pattern unless...
like image 169
zx81 Avatar answered Dec 07 '25 18:12

zx81



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!