php sprintf - 重复参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7674058/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
sprintf - repeating arguments
提问by Savageman
I want to format a string with sprintf
but repeating many times an argument. see..
我想格式化一个字符串,sprintf
但多次重复一个参数。看..
$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.
考虑到要格式化的字符串,我想将第二个 arg 重复两次。
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??
有办法吗??
回答by Savageman
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
注意:格式字符串使用单引号,否则你会得到PHP Notice: Undefined variable: s in /path/to/tofile:line
You can also escape the $
with a \
if you are using double quotes.
如果您使用双引号,您也可以$
使用 a\
转义。