pila pila - 4 months ago 15
PHP Question

Replace Array Callback

I have a string like:


"Hello ? my name is ? and i am ? years old."



Every "
?
" is a variable and I want to replace each variable by an array. So I have this array:

$data = array('Mister,','Tom','30');


So I am looking for a clean way to transform all
?
by its equally array index, so that I get:


"Hello Mister, my name is Tom and i am 30 years old."


Also I want to pass a function like
ucfirst()
to each array entry when they are replaced.

Anybody has an idea how to do it?

Answer Source

Using preg_replace_callback:

$str = "Hello ? my name is ? and i am ? years old.";
$data = array('Mister,','Tom','30');
$str = preg_replace_callback('/\?/', function($match) use(&$data) {
    return ucfirst(array_shift($data));
}, $str);