1

I want to repalce an array with a new one but only the first string is replaced. The new array is from a mysql table so I cant specify the exact strings.

$str = "##Random Stirng## ..... ##Random Stirng##";
$pattern = array ("str1" => "first replacement", "str2" => "second replacement");
$replacement = array('/##[^#]+##/','/##[^#]+##/');
echo preg_replace($replacement, $pattern, $str);

I want to replace the first IP-Address with the first replacement and the secon IP-address with the second replacement but instead both IP-Addresses are replaced with the first replacement.

5
  • 1) You've exchanged pattern & replacement in the preg_replace call. 2) Please, give some example strings and expected result. Commented Jul 23, 2019 at 10:04
  • seems like, first replacement become input for second replacement. works based upon reference itself. Commented Jul 23, 2019 at 10:06
  • "str2" => "second replacement missing double quotes at the end Commented Jul 23, 2019 at 10:07
  • @RakeshJakhar seems like that is typo while raising this question itself. Commented Jul 23, 2019 at 10:08
  • should array keys be the same? Commented Jul 23, 2019 at 11:15

2 Answers 2

2

preg_replace_callback is your friend:

$str = "##Random String## ..... ##Random String##";
$replacement = array ("first replacement", "second replacement");
$i = 0;
$res = preg_replace_callback(
            '/##[^#]+##/', 
            function($m) use(&$i, $replacement) {
                return $replacement[$i++];
            },
            $str);
echo $res;

Output:

first replacement ..... second replacement
Sign up to request clarification or add additional context in comments.

1 Comment

thank you very much. I didnt understand how preg replace callback worked so I had to read about it first. but it worked.
0

You need to use str_replace

$str = "##Random Stirng## ..... ##Random Stirng##";
$pattern = array("Random Stirng", "Random Stirng");
$replacement = array('1','2');
echo str_replace($pattern, $replacement, $str);

1 Comment

this is only an example. I have a big mysql table with many IP-adresses that need to be replaced. That's why I put them between the "##".

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.