开发者

PHP sprintf escaping %

开发者 https://www.devze.com 2023-01-15 01:18 出处:网络
I want the following output:- About to deduct 50% of € 27.59 from your Top-Up account. when I do something like this:-

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?


Escape it with another %:

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


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


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


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)


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

0

精彩评论

暂无评论...
验证码 换一张
取 消