在 sprintf() 的格式字符串中多次访问一个变量

发布于 2024-12-08 14:44:38 字数 381 浏览 0 评论 0原文

我想用 sprintf 格式化一个字符串,但多次重复一个参数。看到..

$str = "Str 1: %s - Str 2: %s - Str 2 again: %s";

考虑到要格式化的字符串,我想重复第二个参数两次。

echo sprintf($str, "I'm string 1", "My name is string 2");

想要的结果是:

Str 1: I'm string 1 - Str 2: My name is string 2 - Str 2 again: My name is string 2

有办法做到这一点吗?

I want to format a string with sprintf but repeating many times an argument. see..

$str = "Str 1: %s - Str 2: %s - Str 2 again: %s";

Considering that string to format, I want to repeat the second arg two times.

echo sprintf($str, "I'm string 1", "My name is string 2");

And the wanted result like:

Str 1: I'm string 1 - Str 2: My name is string 2 - Str 2 again: My name is string 2

There's a way to do that??

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

相对绾红妆 2024-12-15 14:44:38

一切都在文档中!

$str = 'Str 1: %1$s - Str 2: %2$s - Str 2 again: %2$s';
echo sprintf($str, "I'm string 1", "My name is string 2");

注意:使用单引号作为格式字符串,否则您将得到 PHP 注意:未定义的变量:/path/to/tofile:line 中的 s

您还可以转义 $如果使用双引号,则带有 \

It's all in the documentation!

$str = 'Str 1: %1$s - Str 2: %2$s - Str 2 again: %2$s';
echo sprintf($str, "I'm string 1", "My name is string 2");

Note: Use single quotes for the format string otherwise you'll get PHP Notice: Undefined variable: s in /path/to/tofile:line

You can also escape the $ with a \ if you are using double quotes.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文