5

Using sprintf() how can I replace multiple placeholders in a string with one value? I know normally you will pass 1 variable for each placeholder, but I understand if you use the format %1$s instead of %s you can pass a single value, but I can't seem to get it to work.

I'm actually using this as a parametrised sql query, but for ease here's a single example

$name   = "Bill";
$string = "hello ?, your name is ? ";
$string = sprintf(str_replace("?","'%1$s'",$string ),$name);

This doesn't seem to work. I'd also like it to work for a single placeholder, e.g.

$name   = "Bill";
$string = "hello ?";
$string = sprintf(str_replace("?","'%1$s'",$string ),$name);
  1. Is it possible to replace multiple placeholders from one value, and 2. Can a single statement be written to handle single or multiple placeholders?

Note: I'm specifically not talking about passing arrays using vsprintf() as there is only 1 value. Seems pointless to me to pass the same value multiple times.

Thanks

0

1 Answer 1

4

Yes and Yes.

It doesn't work because you are evaluating $s in str_replace. As a rule of thumb, I always use ' instead of " when declaring string literals.

$name   = 'Bill';
$string = 'hello ?, your name is ? ';
$string = sprintf(str_replace('?','\'%1$s\'',$string ),$name);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.