Harts
Harts

Reputation: 4103

php how to match @@MESSAGE@@

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

Answers (3)

Herbert
Herbert

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

Casimir et Hippolyte
Casimir et Hippolyte

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

Martin Ender
Martin Ender

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.

Working demo.

Upvotes: 2

Related Questions