$needle = array("Arr","Arr:","Arrang");
$haystack = " Arr is the proper way of Arr.";
echo str_replace($needle, "Arrangement", $haystack);
打印:Arrangement是Arrangement的正确方式
想要:Arrangement是Arr的正确方式。
最佳答案
将 preg_replace
与 implode
和数组分隔符一起使用。分隔符 \s|
充当 或
语句,使用您的数组创建的正则表达式模式:
$needle = array("Arr","Arr:","Arrang");
$haystack = "Arr: is the proper way of Arr.";
echo preg_replace("/".implode("\s|",$needle)."\s/", "Arrangement ", $haystack, 1);
结果:
Arrangement is the proper way of Arr.
关于php - 字符串仅用php中数组中的单词替换第一次出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33317704/