我试图了解更多关于PHP函数sprintf(),但php.net没有帮助我,因为我仍然困惑,为什么要使用它?
看看下面的例子。
为什么用这个:
$output = sprintf("Here is the result: %s for this date %s", $result, $date);
当这样做是一样的,更容易写IMO:
$output = 'Here is the result: ' .$result. ' for this date ' .$date;
我是不是遗漏了什么?
Sprintf()非常类似于printf()。如果您了解printf()的详细信息,那么sprintf()甚至vsprintf()都不难理解。
sprintf()与printf()的一个不同之处在于,您需要声明一个变量来捕获函数的输出,因为它不直接打印/回显任何内容。让我们看看下面的代码片段:
printf("Hello %s", "world"); // "Hello world"
sprintf("Hello %s", "world"); // does not display anything
echo sprintf("Hello %s", "world"); // "Hello world"
$a = sprintf("Hello %s", "world"); // does not display anything
echo $a;// "Hello world"
希望这能有所帮助。
sprintf的另一个用途是在本地化的应用程序中,因为sprintf的参数不必按照它们在格式字符串中出现的顺序排列。
例子:
$color = 'blue';
$item = 'pen';
sprintf('I have a %s %s', $color, $item);
但是像法语这样的语言对单词的顺序是不同的:
$color = 'bleu';
$item = 'stylo';
sprintf('J\'ai un %2$s %1$s', $color, $item);
(是的,我的法语很烂:我在学校学过德语!)
实际上,您可以使用gettext来存储本地化的字符串,但您可以理解。
Sprintf()非常类似于printf()。如果您了解printf()的详细信息,那么sprintf()甚至vsprintf()都不难理解。
sprintf()与printf()的一个不同之处在于,您需要声明一个变量来捕获函数的输出,因为它不直接打印/回显任何内容。让我们看看下面的代码片段:
printf("Hello %s", "world"); // "Hello world"
sprintf("Hello %s", "world"); // does not display anything
echo sprintf("Hello %s", "world"); // "Hello world"
$a = sprintf("Hello %s", "world"); // does not display anything
echo $a;// "Hello world"
希望这能有所帮助。
即使我认为同样的事情,除非我最近使用它。当您根据用户输入生成文档时,这将很方便。
"<p>Some big paragraph ".$a["name"]." again have tot ake care of space and stuff .". $a["age"]. "also would be hard to keep track of punctuations and stuff in a really ".$a["token"]. paragarapoh.";
WHich可以很容易地写成
sprintf("Some big paragraph %s. Again have to take care of space and stuff.%s also wouldnt be hard to keep track of punctuations and stuff in a really %s paragraph",$a,$b,$c);