Wol*_*'08 33 html php xml string-literals
我正在查看Webmonkey的PHP和MySql教程,第2课.我认为这是一个PHP文字.什么%s意思?print_f()至少在前几个代码块中,它位于while循环中的函数内部.
printf("<tr><td>%s %s</td><td>%s</td></tr>n", ...
Tiv*_*vie 47
printf或sprintf字符前面带有%符号的是占位符(或标记).它们将被作为参数传递的变量替换.
例:
$str1 = 'best';
$str2 = 'world';
$say = sprintf('Tivie is the %s in the %s!', $str1, $str2);
echo $say;
Run Code Online (Sandbox Code Playgroud)
这将输出:
Tivie是世界上最好的!
注意:有更多占位符(%s代表字符串,%d代表dec数字等等)
订购:
传递参数的顺序很重要.如果你用$ str2切换$ str1为
$say = sprintf('Tivie is the %s in the %s!', $str2, $str1);
Run Code Online (Sandbox Code Playgroud)
它会打印出来
"蒂维是世界上最好的!"
但是,您可以更改这样的参数的阅读顺序:
$say = sprintf('Tivie is the %2$s in the %1$s!', $str2, $str1);
Run Code Online (Sandbox Code Playgroud)
这将正确打印句子.
另外,请记住,PHP是一种动态语言,不需要(或支持)显式类型定义.这意味着它根据需要调整变量类型.在sprint中,这意味着如果您将"string"作为数字占位符(%d)的参数传递,则该字符串将转换为数字(int,float ...),这可能会产生奇怪的结果.这是一个例子:
$onevar = 2;
$anothervar = 'pocket';
$say = sprintf('I have %d chocolate(s) in my %d.', $onevar, $anothervar);
echo $say;
Run Code Online (Sandbox Code Playgroud)
这将打印
我的0中有2个巧克力.
更多阅读PHPdocs
Ned*_*der 12
In printf,%s是一个占位符,用于插入字符串的数据.额外的参数printf是要插入的值.它们在位置上与占位符相关联:第一个占位符获取第一个值,第二个占位符获取第二个值,依此类推.