我试图了解更多关于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;
我是不是遗漏了什么?
即使我认为同样的事情,除非我最近使用它。当您根据用户输入生成文档时,这将很方便。
"<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);
使用sprintf()函数而不是普通连接的优点是,您可以对要连接的变量应用不同类型的格式。
在你的情况下,你做到了
$output = sprintf("Here is the result: %s for this date %s", $result, $date);
and
$output = 'Here is the result: ' .$result. ' for this date ' .$date;
让我们输入$result = 'passed';日期= '23 ';
使用普通的连接,你只能得到输出:
Here is the result: passed for this date 23rd
然而,如果你使用sprintf(),你可以得到一个修改后的输出,如:
$output = sprintf('Here is the result: %.4s for this date %.2s',$result,$date);
echo $output;
输出:
Here is the result: pass for this date 23
你为什么要用它?
在为语言字符串使用(外部)源时,它被证明非常有用。如果你在一个给定的多语言字符串中需要固定数量的变量,你只需要知道正确的顺序:
en.txt
not_found = "%s could not be found."
bad_argument = "Bad arguments for function %s."
bad_arg_no = "Bad argument %d for function %s."
hu.txt
not_found = "A keresett eljárás (%s) nem található."
bad_argument = "Érvénytelen paraméterek a(z) %s eljárás hívásakor."
bad_arg_no = "Érvénytelen %d. paraméter a(z) %s eljárás hívásakor."
在多种语言中,插入的变量甚至不必在开头或结尾,只是它们的顺序很重要。
当然,你可以编写自己的函数来执行这个替换,毫无疑问,甚至会有一些小的性能提升,但它要快得多(假设你有一个类Language来读取语言字符串):
/**
* throws exception with message($name = "ExampleMethod"):
* - using en.txt: ExampleMethod could not be found.
* - using hu.txt: A keresett eljárás (ExampleMethod) nem található.
*/
throw new Exception(sprintf(Language::Get('not_found'), $name));
/**
* throws exception with message ($param_index = 3, $name = "ExampleMethod"):
* - using en.txt: Bad argument 3 for function ExampleMethod.
* - using hu.txt: Érvénytelen 3. paraméter a(z) ExampleMethod eljárás hívásakor.
*/
throw new Exception(sprintf(Language::Get('bad_arg_no'), $param_index, $name));
它还带有printf的全部功能,因此也是格式化多种类型变量的一行程序,例如:
浮点数输出精度,或
用前导零填充整数。