如何用 preg_replace 替换两个子字符串?

How to replace two substrings with preg_replace?

我想互相替换两个子字符串,如

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

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

我用preg_replace来匹配替换词,

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

但是,如何将 WORD2 更改为 WORD1(原来的 $str)?

问题是更换要同时进行。否则,word1改成word2又会改成word1

如何同时进行替换?

您可以使用 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);

参见PHP demo

如果WORD是Unicode字符串,还要加上u修饰符,'~\b(?:WORD1|WORD2)\b~u'.

\b(?:WORD1|WORD2)\b 模式匹配 WORD1WORD2 作为整个单词,然后,在用作替换参数的匿名函数内部,您可以检查匹配值并应用每个案例的自定义替换逻辑。

换一种方式。

如果使用中间字符,可以逐步替换。我也更喜欢 preg_replace_callback() ,只是为了说明我的意思:

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