Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP sprintf escaping %

People also ask

How do you escape percentage in Sprintf?

It is very easy. Put another % in front of the original % to escape it.

What does sprintf () function do in PHP?

PHP String sprintf() function. The sprintf() is an in-built function of PHP which writes a formatted string to a variable. It returns a formatted string.

How do you escape a slash in PHP?

In PHP, an escape sequence starts with a backslash \ . Escape sequences apply to double-quoted strings. A single-quoted string only uses the escape sequences for a single quote or a backslash.


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)