PHP sprintf escaping %

PhpEscapingPrintf

Php Problem Overview


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?

Php Solutions


Solution 1 - Php

Escape it with another %:

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

Solution 2 - Php

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 - Php

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

Solution 4 - Php

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 - Php

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSandeepan NathView Question on Stackoverflow
Solution 1 - PhpBoltClockView Answer on Stackoverflow
Solution 2 - Phpuser8228837View Answer on Stackoverflow
Solution 3 - PhpMRMPView Answer on Stackoverflow
Solution 4 - PhpSinan EldemView Answer on Stackoverflow
Solution 5 - Php3eightyView Answer on Stackoverflow