简体   繁体   中英

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);

Prints: Arrangement is the proper way of Arrangement

Want: Arrangement is the proper way of Arr.

Use preg_replace with an implode and delimiter for your array. The delimiter \\s| acts as an or statement with the regex pattern that your array creates:

$needle = array("Arr","Arr:","Arrang");
$haystack = "Arr: is the proper way of Arr.";
echo preg_replace("/".implode("\s|",$needle)."\s/", "Arrangement ", $haystack, 1);

Result :

Arrangement is the proper way of Arr.

Try preg_replace . The 1 here means match on the first instance only. /string/ searches for the string.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM