Reputation: 4103
If I have something like this
This is Before HELLO
@@MESsage@@
@@MESSAGE@@
Hello @@MESSAGE@@ssd
This is After
how can I match only @@MESSAGE@@ ? I tried this and it does not work
preg_replace('/\b@@MESSAGE@@\b/u', xxx, xxxy);
Upvotes: 0
Views: 62
Reputation: 5778
To replace every occurrence use:
preg_replace('/@@message@@/i', xxx, xxxy);
To replace every @@MESSAGE@@ in all caps use:
preg_replace('/@@MESSAGE@@/', xxx, xxxy);
To replace only @@MESSAGE@@ by itself use
preg_replace('/\B@@MESSAGE@@\B/', xxx, xxxy);
If the last case is the one you're looking for, then please accept m.buettner's answer since that's where I got it.
Upvotes: 2
Reputation: 89574
You can use this to be sure to have white characters around your target:
preg_replace('~(?:^|\s)\K@@MESSAGE@@(?=\s|$)~', $replacement, $subject);
Upvotes: 0
Reputation: 44279
The problem are the word boundaries \b
. They match between word and non-word characters, where a word character is a letter, digit or underscore. Because @
is not a word character, you require it to be surrounded by those, instead of the opposite. Use a non-word boundary instead:
preg_replace('/\B@@MESSAGE@@\B/', $replacement, $input);
No need for the u
modifier by the way.
Upvotes: 2