Home > php教程 > php手册 > php中sprintf函数用法详细

php中sprintf函数用法详细

WBOY
Release: 2016-05-25 16:47:45
Original
2102 people have browsed it

以前听老师讲过sprintf()函数需要使用echo方 法才可以讲格式化后的字符串显示输出,下面我来看一下简单的方法.

我在阅读一些资料,书籍的时候总是总是会看到如下这样的代码

实例代码如下:

$query = sprintf('INSERT INTO %sUSER (USERNAME, PASSWORD, ' .  
   'EMAIL_ADDR, IS_ACTIVE, PERMISSION) VALUES ("%s", "%s", "%s", %d, %d)',  
DB_TBL_PREFIX,  
   mysql_real_escape_string($this->username, $GLOBALS['DB']),  
   mysql_real_escape_string($this->password, $GLOBALS['DB']),  
  mysql_real_escape_string($this->emailAddr, $GLOBALS['DB']),  
   $this->isActive,  
$this->permission);
Copy after login

这边使用了sprintf来格式化字符串,这样的写法和直接用字符串连接符连接起来的写法有什么区别吗.或者说这样更加严谨

printf()函数与sprintf()函数的语法格式为:

int printf(string $format[,mixed $arg1[,mixed args2...]])
string sprintf(string $format[,mixed $arg1[,mixed args2...]])
Copy after login

一个小例子,实例代码如下:

PHP中echo,print,printf,sprintf的区别

<?PHP 
$str=&#39;let\&#39;s study php!&#39;; 
echo $str."<br/>"; 
$number=print $str."<br/>"; 
echo $number."<br/>"; 
$format="%b%c%d"; 
$number1=printf($format,88,88,88); 
echo "<br/>".$number1; 
echo "<br/>".sprintf($format,88,88,88); 
?>
Copy after login

echo,print,printf,sprintf的介绍

print输出方式的返回值为int类型的,返回值永远是1,print的语法格式如下:

int print(string $str)

echo输出方式是没有返回值的,echo的语法格式如下:

void echo(string $str[,string $str1...])

在PHP中,一般情况下echo和print是可以通用的,但是在某些情况下两种方式也是有区别的,具体表现在:

1)echo支持多个参数,但是print只支持一个参数

2)echo返回值为void,print有一个永远为1的返回值


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template