0

php

$nn="ab bc cd cd ab";
$tttt=str_ireplace("cd","aaa",$nn);
$tt=str_ireplace("ab","aaa",$tttt);

but the below coding is not working

$nn="ab bc cd cd ab";
$tttt=str_ireplace("cd" or "ab","aaa",$nn);

The output is "aaa bc aaa aaa aaa".PLease help me in simplyfying it.because there are lot more str replaces for various words.

4
  • Use an array with foreach. Commented Aug 8, 2015 at 17:25
  • Look up preg_replace Commented Aug 8, 2015 at 17:26
  • You have a question in PHP about the function str_ireplace, so why don't you simply look into the manual? -> php.net/manual/en/function.str-ireplace.php <- Answer is there Commented Aug 8, 2015 at 17:26
  • Is this some kind of homework/school project? Other user: stackoverflow.com/q/31895327/3933332 but very similar coding style, variable names and writing style. Commented Aug 8, 2015 at 17:33

2 Answers 2

1

You use array in first parameter of str_ireplace.

$nn="ab bc cd cd ab";
$replace_words = array("ab", "cd");
$tttt = str_ireplace($replace_words, "aaa", $nn);
Sign up to request clarification or add additional context in comments.

Comments

0

You may use preg_replace which accepts regex as the first argument. ab|cd would match ab or cd.

preg_replace('~cd|ab~i', 'aaa', $nn);

And add i modifier for doing case-insensitive match.

2 Comments

No need for a regex here, since the function also takes an array as argument. (But it would work too :)
Even the manual agrees with me: If you don't need fancy replacing rules, you should generally use this function instead of preg_replace() with the i modifier. :]

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.