1

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?

1
  • strtr($str, ['WORD1'=>'WORD2', 'WORD2'=>'WORD1']); Commented Oct 25, 2018 at 13:12

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.