在php中,只使用数组中的单词替换第一次出现的单词


String replace first occurrence only with a word from an array in 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.

为您的数组使用preg_replaceimplode和分隔符。分隔符's|使用数组创建的regex模式充当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.

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

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