简体   繁体   中英

php sprintf with array

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

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);

PHP 5.6+中vsprintf的替代品

sprintf("some text %s another text %s extra text %s", ...$array);

Here you have to use vsprintf() instead of sprintf() .

sprintf() accepts only plain variables as argument. But you are trying to pass an array as argument.

For that purpose you need vsprintf() which accepts array as argument.

For example in your case:

"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 

To achieve what you want you have to do the following:

$output = vsprintf("some text %s another text %s extra text %s",$array);
echo $output;

Output:

some text match the first another text match the second extra text match the third
$rv = array(1,2,3,4);
sprintf('[deepak] yay [%s]', print_r($rv, true))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM