PHP字符串的处理(三)-字符串的输出

1.echo()

echo()实际不是一个函数,是一个语言结构,不需要使用括号

<?php
    $str = "test";
    echo $str."<br>";  //输出test
    echo $str." of php.<br>";  //使用.连接多个字符串,输出test of php.
    echo "test","test1","test2"; //输出用逗号多个参数,输出testtest1test2
?>

2.print()

print()函数的功能和echo()函数一样,但是执行效率没有echo()函数高

3.printf()

<?php
    $str = "admin";
    $number = 123;
    printf("His name is %s,he is %u old.",$str,$number);
    printf("The book is %0.2f$",$number);  //把整型$number按浮点数输出,并保留小数点后两位

    $strs = "He is %1$s,he has %2$d children.Their dad is %1$s,He is %2$d old.";
    printf($strs,$str,$number);  //按照占位符输出多次变量,%1$s为第一个参数
?>

函数printf()中常用的字符串格式

%s:字符串

%u:无符号十进制数

%f:浮点数(本地设置)

%F:浮点数(非本地设置)

%%:返回百分比符号

%b:二进制数

%c:依照ASCII值的字符

%d:带符号十进制数

%o:八进制数

%x:十六进制,小写字母

%X:十六进制,大写字母

4.sprintf()

用法和printf()相似,它不输出字符串,而是把格式化的字符串以返回值的形式写入一个变量中

<?php
    $str = "admin";
    $txt = sprintf("He is %s",$str);
    echo $txt; //需要的时候使用格式化的$txt
?>
原文地址:https://www.cnblogs.com/sch01ar/p/7668942.html