Search code examples
phppreg-replacepreg-replace-callback

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?


Solution

  • 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.