Sami
Sami

Reputation: 765

PHP : find all occurrences inside pattern and replace each one with different value

I have a string that is like this :

Hello my name is [foo], I'm from [foo] 

Then I declare an array :

$foo = array('Sam', 'Tunisia');

How can I find all occurence of [foo] in the text and replace the first one with $foo[0], the second with $foo[1] ... The result shoud be like this :

 Hello my name is Sam, I'm from Tunisia

PS : I have to use the same pattern [foo]

Upvotes: 0

Views: 88

Answers (1)

Darragh Enright
Darragh Enright

Reputation: 14136

As suggested by @Rizer123, use preg_replace_callback(). For example:

<?php

$str = "Hello my name is [foo], I'm from [foo]";
$foo = ['Sam', 'Tunisia'];

// note: passing `$foo` by reference. This allows you to
// unshift entries for each match. If there are more matches
// in `$str` than elements in the `$foo` array, `array_shift()`
// will simply return `null`

echo preg_replace_callback('/\[foo\]/', function() use (&$foo) {
    return array_shift($foo);
}, $str);

Yields:

Hello my name is Sam, I'm from Tunisia

For more reading, see the PHP docs for:

Hope this helps :)

Upvotes: 3

Related Questions