'PHP sprintf escaping %

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?



Solution 1:[1]

Escape it with another %:

$stringWithVariables = 'About to deduct 50%% of %s %s from your Top-Up account.';

Solution 2:[2]

It is very easy.

Put another % in front of the original % to escape it.

For example,

$num=23;
printf("%%d of 23 = %d",$num);

Output:

%d of 23 = 23

Solution 3:[3]

For add % in your language string, you just need to add double percent %% instead of one

Solution 4:[4]

This works for me:

sprintf(
    '%s (Cash Discount: %%%s, Deferred Discount: %%%s)',
    $segment->name,
    $segment->discount_cash,
    $segment->discount_deferred,
)

// Gold (Cash Discount: %25, Deferred Discount: %20)

Solution 5:[5]

What about this:

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

Just add your percent sign in your variables array

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 BoltClock
Solution 2
Solution 3
Solution 4 Sinan Eldem
Solution 5 3eighty