PHP 实用函数sprintf()详解

1. 格式

sprintf(format, arg1, arg2, arg3,..) 把格式化的字符串写入到变量中,加粗字体为必需参数。

2. 说明

替换是逐步执行的,按参数顺序,但是如果%符号多于参数个数,则实用占位符(由数字和\$组成),例子:

<?php
$number = 123;
$txt = sprintf("With 2 decimals: %1\$.2f<br />With no decimals: %1\$u",$number);
echo $txt;
?>

输出:

With 2 decimals: 123.00 
With no decimals: 123

3. format参数中可用值:
  • %% - 返回百分比符号
  • %b - 二进制数
  • %c - 依照 ASCII 值的字符
  • %d - 带符号十进制数
  • %e - 可续计数法(比如 1.5e+3)
  • %u - 无符号十进制数
  • %f - 浮点数(local settings aware)
  • %F - 浮点数(not local settings aware)
  • %o - 八进制数
  • %s - 字符串
  • %x - 十六进制数(小写字母)
  • %X - 十六进制数(大写字母)

官方解释见:http://www.w3school.com.cn/php/func_string_sprintf.asp

posted @ 2014-12-26 11:34  精诚所至金石溶灰  阅读(235)  评论(0编辑  收藏  举报