I have an array witch match string placeholders as follow:
"some text %s another text %s extra text %s"
and the array:
$array[0] match the first %s $array[1] match the second %s $array[2] match the third %s
I thought it could be done using the sprintf function as follow:
$content = sprintf("some text %s another text %s extra text %s", $array);
but this return the too few arguments error, i tried to use implode:
$content = sprintf("some text %s another text %s extra text %s", implode(",",$array));
thanks in advance
Not in any traditional sense, as PHP's sprintf doesn't support any of the really dangerous conversions like %n . A user-controlled format string can still cause some limited havoc (consider %99999999s ), but about the worst I think it could do would be to consume memory and time. Save this answer.
The sprintf() is an in-built function of PHP which writes a formatted string to a variable. It returns a formatted string.
%s is a type specifier which will be replaced to valuable's value (string) in case of %s . Besides %s you can use other specifiers, most popular are below: d - the argument is treated as an integer, and presented as a (signed) decimal number.
The vsprintf is defined in the stdio. h header file. It uses a format string and corresponding arguments to generate a string stored in the provided destination string.
Use vsprintf
instead of sprintf
. It takes an array parameter from which it formats the string.
$content = vsprintf("some text %s another text %s extra text %s", $array);
An alternative to vsprintf
in PHP 5.6+
sprintf("some text %s another text %s extra text %s", ...$array);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With