0

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.

2

1 Answer 1

1

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

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.