我试图了解更多关于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"

希望这能有所帮助。

其他回答

即使我认为同样的事情,除非我最近使用它。当您根据用户输入生成文档时,这将很方便。

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

这样更容易翻译。

echo _('Here is the result: ') . $result . _(' for this date ') . $date;

翻译(gettext)字符串现在是:

结果如下: 在这个日期

当翻译成其他语言时,这可能是不可能的,或者会导致非常奇怪的句子。

如果你有

echo sprintf(_("Here is the result: %s for this date %s"), $result, $date);

翻译(gettext)字符串现在是:

结果如下:此日期%s的%s

哪个更有意义,翻译成其他语言更灵活

参数与使用模板的参数相同。您需要将Textsleev与实际的变量值分开。除了我们提到的sprintf的额外功能之外,它只是一个样式问题。

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"

希望这能有所帮助。

我用它来发送给用户的消息或其他“漂亮”类型的功能。例如,如果我知道我将使用用户的名字。

$name = 'Some dynamic name';

并在这种情况下使用多个消息。(例如,屏蔽或关注其他用户)

$messageBlock = 'You have blocked %s from accessing you.';
$messageFollow = 'Following %s is a great idea!';

你可以创建一个通用函数,对用户做一些事情,并添加这个字符串,无论句子的结构是什么,它都应该看起来很漂亮。我总是不喜欢仅仅把字符串附加在一起,不断地使用点符号,关闭和重新打开字符串,只是为了让一个句子看起来更好。我一开始是一个粉丝,像大多数人一样,但这似乎非常有用,当多个字符串需要被操纵,你不想硬编码变量的位置在每次。

想想看,哪个更好看?

return $messageOne === true ? $name.'. Please use the next example' : 'Hi '.$name.', how are you?'

Or

$message = $messageOne === true ? 'Option one %s' 
: ($messageTwo === true ? 'Option Two %s maybe?' : '%s you can choose from tons of grammatical instances and not have to edit variable placement and strings');

return sprintf($message, $name);

当然,这是一个额外的步骤,但如果你的条件检查做了一堆其他功能的事情,然后引号和追加开始在编码的功能。