当前位置: 首页 > 网络学院 > 服务端脚本教程 > PHP > vsprintf() 函数
The vsprintf() function writes a formatted string to a variable.
vsprintf()函数的作用是:输出格式化字符串到变量。
Unlike sprintf(), the arguments in vsprintf(), are placed in an array. The array elements will be inserted at the percent (%) signs in the main string. This function works "step-by-step". At the first % sign, the first array element is inserted, at the second % sign, the second array element is inserted, etc.
与fprintf()函数不同,vsprintf()函数中的自变量是位于数组中的,数组元素的字符串之前都要加上百分号(%)。这个函数是“一步一步[step-by-step]”按顺序执行。在第一个%后,将插入第一个数组元素;在第二个%后,将插入第二个数组元素,依次类推。
vsprintf(format,argarray) |
Parameter参数 | Description描述 |
---|---|
format | Required. Specifies the string and how to format the variables in it. 必要参数。指定字符串,以及如何定义其中变量的格式。 Possible format values:
Additional format values. These are placed between the % and the letter (example %.2f):
Note: If multiple additional format values are used, they must be in the same order as above. |
argarray | Required. An array with arguments to be inserted at the % signs in the format string 必要参数。指定在格式化字符串中插在%之后的带有自变量的数组对象 |
Note: If there are more % signs than arguments, you must use placeholders. A placeholder is inserted after the % sign, and consists of the argument- number and "$". See example three.
注意:注意:如果这里的%比自变量更多,你必须使用占位符[placeholders]。占位符是安插在%之后的,它是由自变量-数字和“$”组成的。具体可以见案例3。
Tip: Related functions: fprintf(), printf(), sprintf(), vfprintf(), and vprintf().
提示:相关函数:printf(), sprintf(), vfprintf(), vprintf(), 和 vsprintf()
<?php $str = "Hello"; $number = 123; $txt = vsprintf("%s world. Day number %u",array($str,$number)); echo $txt; ?> |
The output of the code above will be:
上述代码将输出下面的结果:
Hello world. Day number 123 |
<?php $num1 = 123; $num2 = 456; $txt = vsprintf("%f%f",array($num1,$num2)); echo $txt; ?> |
The output of the code above will be:
上述代码将输出下面的结果:
123.000000456.000000 |
Use of placeholders:
使用占位符:
<?php $number = 123; $txt = vsprintf("With 2 decimals: %1$.2f <br />With no decimals: %1$u",array($number)); echo $txt; ?> |
The output of the code above will be:
上述代码将输出下面的结果:
With 2 decimals: 123.00 With no decimals: 123 |