1

I have a string e.g.

$str = "name is: ?, role is: ?";

and I have an array, e.g.

$array = array('John','Carpenter');

I want to replace each ? in the string with the corresponding item in the array, i.e. the first ? gets replaced with John and the second ? gets replaced with Carpenter.

The number of values in the array will always be the same as the number of ? in the string.

I have come up with the following code to do this:

for($i=0;$i<count($array);$i++) {
    $str = preg_replace('/\?/',$array[$i],$str,1);
}

My question is, is this the most efficient way of doing what I want to do? If you know of a method, or more efficient way of doing this, please could you post an answer?

Many thanks.

1
  • 4
    $str = vsprintf(str_replace('?','%s',$str), $array); Commented Mar 20, 2014 at 14:16

2 Answers 2

2

You should use vsprintf to do that:

$format = "name is: %s, role is: %s";
$array = array('John','Carpenter');

$str = vsprintf($format, $array);

echo $str;
// name is: John, role is: Carpenter
Sign up to request clarification or add additional context in comments.

Comments

1

Use preg_replace_callback(), which for each match calls a user-provided function that can return a different replacement each time:

$i = 0;
$str = preg_replace_callback('/\?/', function ($m) use ($arr, &$i) {
    return $arr[$i++];
}, $str);

1 Comment

perhaps a little overengineered for my purpose? seems the concensus is that vsprintf is what i need. thx for taking the time to answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.