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

2
  • This even shows Arrangementement is the proper way of Arrangementement Commented Oct 24, 2015 at 11:39
  • How do you choose which word to replace with? Commented Oct 24, 2015 at 11:51

2 Answers 2

3

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.
Sign up to request clarification or add additional context in comments.

5 Comments

if $haystack = "Arr is the proper way of Arr:";, still output shows Arrangement is the proper way of Arr.
@SubinThomas thats what is being looked for isnt it?
need "Arr","Arr:","Arrang" all these to be replaced, I think @Rich
Yep, so we only do it once, and Arr gets found first over Arr: and Arrang., because its a shorter string.
@Octopi : Still need clarity of question. Not clear his needs.
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.