pila pila - 9 months ago 62
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
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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download