2

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?

4 Answers 4

5

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

Comments

1

str_replace can do that (in combination with array_map:

$array = array('Mister,', 'Tom', '30');
$new_string = str_replace(array('?', '?', '?'),
    array_map(function($v) { return ucfirst($v); }, $array),
    $old_string
);

3 Comments

that won't work as it replaces all occurences of ? with Mister
it replaces all occurrences of ? with Array
@NikoSams: My bad, that only works the other direction (search being an array, replace a string).
0

sprintf() with call_user_func_array()?

array_walk()?

Comments

-1
$string = 'String ? etc etc';
$string = preg_replace("/?/",array_shift($data), $string, 1);
$string = preg_replace("/?/",array_shift($data), $string, 1);
$string = preg_replace("/?/",array_shift($data), $string, 1);

echo $string

3 Comments

Why the downvote? This is the simplest code. It could easily be put in a loop. The 1 at the end is a limiter which says only once a time.
It's not my downvote. But i think the person thought it repeated too much.
Oh, I suppose i should put it into a loop then. Thanks! It was my upvote though ;)

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.