Samson
Samson

Reputation: 352

How to replace multiple occurrence with each unique value using preg_replace in php

I have some words in a paragraph and I want to replace all with different values using PHP preg_replace() function and I solving with following code snippet but not able to solve that one.

$str = "abc abc abc abc abc abc";
$strArr = ["xyz", "pqr", "mnl", "01j", "pqr", "lmn"];

$count = preg_match_all("/abc/is", $str, $matches);
for($i = 0; $i < $count; $i++) {
    preg_replace('/abc"([^\\"]+)"/', $strArr[$i], $str);
}
// At the end I need to get like as following
$str = "xyz pqr mnl 01j pqr lmn";

It is replacing only one first occurrence.

Upvotes: 0

Views: 406

Answers (1)

u_mulder
u_mulder

Reputation: 54831

You can do it with preg_replace_callback:

$str = "abc abc abc abc abc abc";
$strArr = ["xyz", "pqr", "mnl", "01j", "pqr", "lmn"];

$count = 0;
echo preg_replace_callback(
    '/abc/',
    function ($v) use ($strArr, &$count) {
        return $strArr[$count++];
    },
    $str
);

Or even without counter:

echo preg_replace_callback(
    '/abc/',
    function ($v) use (&$strArr) {
        return array_shift($strArr);
    },
    $str
);

Upvotes: 1

Related Questions