26

Like

$args = (
 'var1' => 'abc',
 'var2' => 'def',
);


$text = sprintf('first var is: %1$s, second one is: %2$s', $args);

Basically the $args variable is dynamic, I don't know if it will have any entries or how many.

The text too, I don't know if it will require variables to be replaced in it, or how many.

How can I make a function like this, that somehow extracts the elements and replaces them in the text if stuff like %s %d, %1$s etc is present?

3
  • If the number of wildcards in the format specifier differs from the number of elements in the array, then what happens? Commented Sep 7, 2011 at 20:46
  • 1
    Throw a php warning or something :) (this shouldn't happen under normal circumstances) Commented Sep 7, 2011 at 20:47
  • if you're referring to the case where there are no wildcards, but there are variables available, then no replacements should be made. But if there are more wild cards then variables, then this would be a error case Commented Sep 7, 2011 at 20:49

1 Answer 1

38

You probably want vsprintf().

Sign up to request clarification or add additional context in comments.

Comments

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.