Googlebot
Googlebot

Reputation: 15683

How to replace two substrings with preg_replace?

I want to replace two substrings with each other, as

$str = 'WORD1 some text WORD2 and we have WORD1.';

$result = 'WORD2 some text WORD1 and we have WORD2.';

I use preg_replace to match the replacing words,

$result = preg_replace('/\bWORD1(?=[\W.])/i', 'WORD2', $str);

but, how can I change WORD2 to WORD1 (in the original $str)?

The problem is that the replacement should be done at the same time. Otherwise, word1 changed to word2 will be changed to word1 again.

How can I make the replacements at the same time?

Upvotes: 1

Views: 55

Answers (2)

hausl
hausl

Reputation: 180

Just as another way.

You can Replace step by step if you use a intermediate-char. I prefere the preg_replace_callback() too, just to be shown what i mean:

$str = 'WORD1 some text WORD2 and we have WORD1.';

$w1 = "WORD1";
$w2 = "WORD2";

$interChr = chr(0);
$str = str_replace($w1, $interChr, $str);
$str = str_replace($w2, $w1, $str);
$str = str_replace($interChr, $w2, $str);

echo $str;
// WORD2 some text WORD1 and we have WORD2.

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626926

You may use preg_replace_callback:

$str = 'WORD1 some text WORD2 and we have WORD1.';
echo preg_replace_callback('~\b(?:WORD1|WORD2)\b~', function ($m) {
    return $m[0] === "WORD1" ? "WORD2" : "WORD1";
}, $str);

See the PHP demo.

If WORDs are Unicode strings, also add u modifier, '~\b(?:WORD1|WORD2)\b~u'.

The \b(?:WORD1|WORD2)\b pattern matches either WORD1 or WORD2 as whole words, and then, inside the anonymous function used as a replacement argument, you may check the match value and apply custom replacement logic for each case.

Upvotes: 3

Related Questions