0

Let say I have a string

$content = "hello . wow . cool . yes!";

It's easy to just replace the dot to another string:

echo preg_replace("/\./", "<img>", $content);

so the output is:

hello <img> wow <img> cool <img> yes!

however, is there any way to replace it one by one?

for example, I have an array and would like to insert them into the string.

$arr = ['<img src="a"/>', '<img src="b"/>', '<img src="c"/>'];

the expected output:

hello <img src="a"/> wow <img src="b"/> cool <img src="c"/> yes!

I can use preg_match_all to get the separator but still have no idea how to replace it respectively.

Thank you for any help.

1 Answer 1

1

Use preg_replace_callback. Store the number of the current full stop in a static variable. Access $arr from the callback with use (). Use modulo in case there are not enough items in $arr.

<?php
$content = 'hello . wow . cool . yes!';
$arr = ['<img src="a"/>', '<img src="b"/>', '<img src="c"/>'];
$content = preg_replace_callback ('/\./', function ($_) use ($arr) {
    static $count = 0;
    return $arr [$count++ % count ($arr)];
}, $content);
echo ($content);

http://sandbox.onlinephpfunctions.com/code/f9115bdb6eb17e30012d987ed1fc4b95e7c10d33.

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.