我试图了解更多关于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在格式化使用数字的字符串时特别有用。例如,

$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

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

sprintf有许多用例,但我使用它们的一种方式是在数据库中存储这样的字符串:'Hello, My Name is %s',或将其作为PHP类中的常量。这样当我想要使用该字符串时,我可以简单地这样做:

$name = 'Josh';
// $stringFromDB = 'Hello, My Name is %s';
$greeting = sprintf($stringFromDB, $name);
// $greetting = 'Hello, My Name is Josh'

本质上,它允许在代码中进行一些分离。如果我在代码中的许多地方使用“Hello, My Name is %s”,我可以在一个地方将其更改为“%s是我的名字”,并且它会自动更新其他任何地方,而不必去到每个实例并在连接中移动。

有时我会得到这样的东西,我认为这更容易阅读:

$fileName = sprintf('thumb_%s.%s', 
                    $fileId,
                    $fileInfo['extension']);

你为什么要用它?

在为语言字符串使用(外部)源时,它被证明非常有用。如果你在一个给定的多语言字符串中需要固定数量的变量,你只需要知道正确的顺序:

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的全部功能,因此也是格式化多种类型变量的一行程序,例如:

浮点数输出精度,或 用前导零填充整数。

这样的:

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

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