如何在PHP中替换字符串中的单个单词?

Goo*_*bot 2 php regex word-boundary str-replace

我需要用数组给出的替换替换单词

$words = array(
'one' => 1,
'two' => 2,
'three' => 3
);

$str = 'One: This is one and two and someone three.';

$result = str_ireplace(array_keys($words), array_values($words), $str);
Run Code Online (Sandbox Code Playgroud)

但这种方法someone改为some1.我需要替换单个单词.

chr*_*s85 5

您可以在正则表达式中使用单词边界来要求单词匹配.

就像是:

\bone\b
Run Code Online (Sandbox Code Playgroud)

会做的.preg_replace使用i修饰符是你想在PHP中使用的.

正则表达式演示:https://regex101.com/r/GUxTWB/1

PHP用法:

$words = array(
'/\bone\b/i' => 1,
'/\btwo\b/i' => 2,
'/\bthree\b/i' => 3
);
$str = 'One: This is one and two and someone three.';
echo preg_replace(array_keys($words), array_values($words), $str);
Run Code Online (Sandbox Code Playgroud)

PHP演示:https://eval.in/667239

输出:

1:这是1和2,有人3.