php 带有数组的php sprintf

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13325698/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 05:10:01  来源:igfitidea点击:

php sprintf with array

phparraysprintf

提问by tarek

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:

我认为可以使用 sprintf 函数完成,如下所示:

$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

提前致谢

回答by FThompson

Use vsprintfinstead of sprintf. It takes an array parameter from which it formats the string.

使用vsprintf代替sprintf。它接受一个数组参数,从中格式化字符串。

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

回答by user634545

An alternative to vsprintfin PHP 5.6+

vsprintfPHP 5.6+的替代方案

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

回答by user634545

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

在这里你必须使用vsprintf()而不是sprintf().

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

sprintf()只接受普通变量作为参数。但是您试图将数组作为参数传递。

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

为此,您需要vsprintf()接受数组作为参数。

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

回答by deeshank

$rv = array(1,2,3,4);
sprintf('[deepak] yay [%s]', print_r($rv, true))