字符串替换首次出现只与php中的数组中的单词

时间:2015-10-24 11:35:13

标签: php

$needle = array("Arr","Arr:","Arrang");
$haystack = " Arr is the proper way of Arr.";
echo str_replace($needle, "Arrangement", $haystack);

打印:Arrangement is the proper way of Arrangement

想要:Arrangement is the proper way of Arr.

2 个答案:

答案 0 :(得分:3)

对阵列使用preg_replace implode和分隔符。分隔符\s|充当or语句,其中包含数组创建的正则表达式模式:

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

答案 1 :(得分:2)

试试preg_replace。这里的1表示仅在第一个实例上匹配。 /string/搜索字符串。

$haystack = "Arr is the proper way of Arr.";
echo preg_replace("/Arr/", "Arrangement", $haystack, 1);