如果已经有名字和邮箱两变量,需要输出 名字:name is 名字, and email is 邮箱
,则一般的写法如下:
<?php $name = 'Ruchee'; $email = 'my@ruchee.com'; printf('%s: name is %s, and email is %s', $name, $name, $email); // 或者 echo sprintf('%s: name is %s, and email is %s', $name, $name, $email);
PHP
的格式化字符串支持一个叫位置标记的用法,C/C++
是没有的,使用它可以声明哪些格式符使用的数据是一致的,如此就可以避免传递多个重复的参数:
<?php $name = 'Ruchee'; $email = 'my@ruchee.com'; printf('%1$s: name is %1$s, and email is %2$s', $name, $email); // 或者 echo sprintf('%1$s: name is %1$s, and email is %2$s', $name, $email);
使用方法是在 %
与类型指代符号之间增加一个序号和一个美元符,由于使用了美元符,所以整个格式化字符串只能是单引号字符串(如果是双引号字符串,则美元符+后续字符会被错误当成变量来解析)
使用位置标记,输出并换行:
<?php $name = 'Ruchee'; $email = 'my@ruchee.com'; printf("%1$s: name is %1$s, and email is %2$s\n", $name, $email); // 错误 printf('%1$s: name is %1$s, and email is %2$s'."\n", $name, $email); // 正确