search
HomeBackend DevelopmentPHP TutorialPHP 字符串操作的 printf() 内置函数用法

php中指出打印输出的函数有很多 最常见的就是  echo  print()   printf()   spintf() 这几个了。


echo 和 print() 功能相同,但是 print( )具有执行成功与否的返回值 (true 和 false)。


使用函数 printf()  和 sprintf() 还可以实现一些更为复杂的格式化输出。 这两个的工作方式基本相同,只是printf() 函数是讲一个格式化的字符串输出到浏览器中,而 sprintf() 函数是返回一个格式化过的字符串。


printf()  基本用法:

echo "you have $total money";

    要使用printf() 函数得到相同的结果,就应该使用如下语句:

printf ("you have %s money", $total );

    格式化字符串中的%s 是转换标记。它的意思是使用后面的变量来替换自己。 在这个例子中它会被解释成字符串$total 的代替。  如果 $total 变量中的值是 25.6,以上两种方法都将打印为25.6 。


printf() 的优点在于,可以使用更有用的转换说明来指定 $total 为一个浮点数(它的后面应该有两位小数点)。 如下所示:

printf("you hava %.2f money ", $total );

经过这行代码格式化处理,存储在 $total 中的25.6 将打印为 25.60 。(但是并不影响变量原始的值)


可以在格式化字符串中使用多个转换标记。 如果有n个转换标记,那么在格式化字符串后面就应该带有n个参数。 每个转换标记默认将按照给出的顺序依次重新格式化。

printf ("you have %.2f money , but shopping %.2f RMB ", $total , $total_shopping );

在这里,第一个转换标记将使用$total 的值, 第二个转换标记将使用变量 $total_shopping 的值。


printf()   %转换标记的语法格式:

%[ 'padding_character] [ - ] [ width ] [ .precision ] type    //中括号内的参数为可选参数

所有的转换标记都以% 开头。

    参数padding_character 将被用来填充变量直至所指定的宽度。该参数的作用就像使用计算器那样在数字前面加零。 默认填充字符是一个空格,如果指定了一个空格或者0 ,就不需要使用 ‘ 单引号作为前缀。 对于任何其他填充字符,必须指定 ’ 单引号前缀。

    字符 - 是可选的。它指明该域中的数据的对齐方式, 该选项默认留空即右对齐,设置了 - 符号,那么就是左对齐(填充字符填充到右边不够的位置)。

    参数 width 是可选的,它告诉printf() 函数在这里将显示的字符宽度(按字符计算)。

    参数 precision 必须是以一个小数点开始。 它用于指明小数点后的精确位数。

    转换标记最后的一部分是一个类型码。 其支持的所有类型如下表所示:

代码类型 意义
b 解释为整数并作为二进制数输出
c 解释为整数并作为字符输出
d 解释为整数并作为小数输出
f 解释为双精度并作为浮点数输出
o 解释为整数并作为八进制数输出
s 解释为字符串并作为字符串输出
u 解释为整数并作为非指定小数输出
x

解释为整数并作为带有小写字母a~f的十六进制数输出

X 解释为整数并作为带有大写字母A~F的十六进制数输出


用法示例:

php > $a = 534 ;php > printf("printf type is %.1f",$a);printf type is 534.0php > printf("printf type is %'u.1f",$a);printf type is 534.0php > printf("printf type is %'u6.1f",$a);printf type is u534.0php > printf("printf type is %'u10.1f",$a);printf type is uuuuu534.0php > printf("printf type is %'u-10.1f",$a);printf type is 534.0uuuuuphp > printf("printf type is %b",$a);printf type is 1000010110php > printf("printf type is %o",$a);printf type is 1026php > printf("printf type is %s",$a);printf type is 534php > printf("printf type is %u",$a);printf type is 534php > printf("printf type is %x",$a);printf type is 216php > $a = 539;php > printf("printf type is %x",$a);printf type is 21b


当在类型转换代码中使用 printf() 函数时,你可以使用带序号的参数方式,这就意味着参数的顺序并不一定要与转换标记中的顺序相同。 例如:

printf ("you have %2\$.2f money , but shopping %1\$.2f RMB ", $total , $total_shopping );

只要直接在 % 符号后添加参数的位置,并且以 $ 符号为结束 。 在这个例子中,2\$ 意味着用列表中的第二个参数替换。这个方法也可以在重复参数中使用。

php > $a = 539;php > $b = 38;php > printf("you have %2\$.2f money , but shopping %1\$.2f RMB! ", $a,$b);you have 38.00 money , but shopping 539.00 RMB! php >



这些函数还有两种可替换版本,分别是 vprintf()  和 vsprintf() 。这些变体函数接受两个参数:格式字符串 和 参数数组, 而不是可变数量的参数。

Statement
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
11 Best PHP URL Shortener Scripts (Free and Premium)11 Best PHP URL Shortener Scripts (Free and Premium)Mar 03, 2025 am 10:49 AM

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Introduction to the Instagram APIIntroduction to the Instagram APIMar 02, 2025 am 09:32 AM

Following its high-profile acquisition by Facebook in 2012, Instagram adopted two sets of APIs for third-party use. These are the Instagram Graph API and the Instagram Basic Display API.As a developer building an app that requires information from a

Working with Flash Session Data in LaravelWorking with Flash Session Data in LaravelMar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

Build a React App With a Laravel Back End: Part 2, ReactBuild a React App With a Laravel Back End: Part 2, ReactMar 04, 2025 am 09:33 AM

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Simplified HTTP Response Mocking in Laravel TestsSimplified HTTP Response Mocking in Laravel TestsMar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

cURL in PHP: How to Use the PHP cURL Extension in REST APIscURL in PHP: How to Use the PHP cURL Extension in REST APIsMar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

12 Best PHP Chat Scripts on CodeCanyon12 Best PHP Chat Scripts on CodeCanyonMar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Announcement of 2025 PHP Situation SurveyAnnouncement of 2025 PHP Situation SurveyMar 03, 2025 pm 04:20 PM

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software