246

I want the following output:-

About to deduct 50% of € 27.59 from your Top-Up account.

when I do something like this:-

$variablesArray[0] = '€';
$variablesArray[1] = 27.59;
$stringWithVariables = 'About to deduct 50% of %s %s from your Top-Up account.';
echo vsprintf($stringWithVariables, $variablesArray);

But it gives me this error vsprintf() [function.vsprintf]: Too few arguments in ... because it considers the % in 50% also for replacement. How do I escape it?

5
  • 2
    @Col. Shrapnel My question is about vsprintf not printf, I am using this for the first time and could not assume the similarity between the two. However, searching escape or escaping in both php.net/printf and php.net/vsprintf both does not show the answer immediately. When I search for %% it shows the answer in php.net/printf but I didn't know about %%!!! Did you search for the answer there before downvoting? Commented Sep 8, 2010 at 10:40
  • @sandeepan: vsprintf belongs in the same family of functions as printf. The correct documentation to find the format, though, is php.net/sprintf. Both pages even point to it: "See sprintf() for a description of format." Didn't you at least click it? Commented Sep 8, 2010 at 10:43
  • 6
    @Col. Shrapnel ok fine let's take php.net/sprintf, where is the answer? It is halfway down the page With printf() and sprintf() functions, escape character is not backslash '\' but rather '%'. What is there to downvote here? It was just not that obvious to me as it was to you. If you find a duplicate question you can better write the link. But I am sure many will find this question helpful. But you won't accept that and you will still say something, I know. Commented Sep 8, 2010 at 10:49
  • oh I thought the second comment was by Col. Shrapnel , sorry Commented Sep 8, 2010 at 10:51
  • 5
    SO should have a flag for RTFM responses. It's almost like people troll just so they can tell people to read the docs. He needed help and asked a question and then someone answered helpfully and got points for it. The world went on and the internet was used to someone's benefit. Meanwhile I'm getting heated over a two year old argument. Commented Jul 2, 2013 at 3:22

1 Answer 1

441

Escape it with another %:

$stringWithVariables = 'About to deduct 50%% of %s %s from your Top-Up account.';
Sign up to request clarification or add additional context in comments.

4 Comments

sprintf("SELECT * FROM ... WHERE name LIKE '%%%s%%%s%%'", $fname, $lname); -- Ugly but it works!
you can add that part with another "%s": sprintf('from %s you can get %s', 'something', '50%')
How do you escape it if the string is dynamic? Let's say, sprintf('This is %s.', the_title())
@madastro str_replace('%', '%%', the_title())

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.