sprintf-重复参数 [英] sprintf - repeating arguments

查看:353
本文介绍了sprintf-重复参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用sprintf格式化字符串,但重复多次参数.见..

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

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

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

所需的结果如:

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

有一种方法可以做到?

推荐答案

全部包含在文档中!

$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

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.

这篇关于sprintf-重复参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆