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

我是不是遗漏了什么?


当前回答

这样更容易翻译。

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

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

其他回答

我发现的最好的理由是,它允许你把所有的语言字符串放在你的语言文件中,人们可以根据需要翻译和排序它们-但你仍然知道,无论字符串的格式是什么-你希望显示用户的名字。

例如,您的网站会在页面顶部显示“欢迎返回[[User]]”。作为程序员,你不知道或不关心UI人员将如何编写它——你只知道用户名将显示在消息中的某个地方。

因此,您可以将消息嵌入到代码中,而不必担心该消息实际上是什么。

只需文件 (EN_US):

...
$lang['welcome_message'] = 'Welcome back %s';
...

然后,通过在实际的php代码中使用它,就可以支持任何语言的任何类型的消息。

sprintf($lang['welcome_message'], $user->name())

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在格式化使用数字的字符串时特别有用。例如,

$oranges = -2.34;
echo sprintf("There are %d oranges in the basket", $oranges);

Output: There are -2 oranges in the basket

Oranges被格式化为整数(-2),但如果使用%u表示无符号值,则会换行为正数。为了避免这种行为,我使用绝对函数abs(),将数字四舍五入,如下所示:

$oranges = -5.67;
echo sprintf("There are %d oranges in the basket", abs($oranges));

Output: There are 5 oranges in the basket

最终的结果是一个具有高可读性、逻辑结构、清晰格式和根据需要灵活添加额外变量的语句。随着变量数量的增加以及操作这些变量的函数的组合,好处变得更加明显。最后一个例子:

$oranges = -3.14;
$apples = 1.5;
echo sprintf("There are %d oranges and %d apples", abs($oranges), abs($apples));

Output: There are 3 oranges and 4 apples

sprintf语句的左边清楚地表达了字符串和期望值的类型,而右边清楚地表达了使用的变量以及如何操作它们。

这样更容易翻译。

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

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

这样的:

"<p>Some big paragraph ".$a["name"]." again have to take care of space and stuff .". $a["age"]. "also would be hard to keep track of punctuations and stuff in a really ".$a["token"]. paragraph.";

也可以写成:

"<p>Some big paragraph {$a['name']} again have to take care of space and stuff .{$a['age']} also would be hard to keep track of punctuations and stuff in a really {$a['token']} paragraph.";

在我看来,这更容易理解,但我可以看到本地化或格式化的用途。