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

时间:2018-10-25 12:45:06

标签: php preg-replace preg-replace-callback

我想彼此替换两个子字符串,

$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

如何同时进行替换?

2 个答案:

答案 0 :(得分:3)

您可以使用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整体匹配,然后,在用作替换参数的匿名函数中,您可以检查匹配值并应用自定义替换每种情况的逻辑。

答案 1 :(得分:1)

只是另一种方式。

如果使用中间字符,则可以逐步替换。我也更喜欢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.