我目前正在使用PHP的str_replace在循环中用另一个替换特定值.
问题是,str_replace将用第二个值替换第一个值的所有实例,而不是按顺序替换它们.例如:
$replacements = array('A', 'one', 'some');
$str = "The quick brown fox jumps over the lazy dog and runs to the forest.";
foreach($replacements as $replace){
$str = str_replace('the', $replace, $str);
}
Run Code Online (Sandbox Code Playgroud)
这将最终回归:
"一只快速的棕色狐狸跳过一只懒狗跑到森林里."
而不是我想要的是什么:
"一只快速的棕色狐狸跳过一只懒狗跑到一些森林里."
这样做最有效的方法是什么?我以为我可以使用preg_replace但我对正则表达式平庸.
未经测试,但我认为这将成功.
$replacements = array('A', 'one', 'some');
$str = "The quick brown fox jumps over the lazy dog and runs to the forest.";
foreach($replacements as $replace){
$str = preg_replace('/the/i', $replace, $str, 1);
}
echo $str;
Run Code Online (Sandbox Code Playgroud)
编辑:添加了i以使其不区分大小写