Home php教程 php手册 PHP sprintf() 函数使用方法详解

PHP sprintf() 函数使用方法详解

Jun 13, 2016 am 10:16 AM
php Instructions Write write function string us Bundle format of Know Detailed explanation

我们知道sprintf() 函数把格式化的字符串写写入一个变量中,我们经常会看到这类代码了,下面我来介绍sprintf() 函数使用方法,有需要的朋友可参考参考。

用法

sprintf(format,arg1,arg2,arg++)

说明
参数 format 是转换的格式,以百分比符号 ("%") 开始到转换字符结束。下面的可能的 format 值:

•%% - 返回百分比符号
•%b - 二进制数
•%c - 依照 ASCII 值的字符
•%d - 带符号十进制数
•%e - 可续计数法(比如 1.5e+3)
•%u - 无符号十进制数
•%f - 浮点数(local settings aware)
•%F - 浮点数(not local settings aware)
•%o - 八进制数
•%s - 字符串
•%x - 十六进制数(小写字母)
•%X - 十六进制数(大写字母)
arg1, arg2, ++ 等参数将插入到主字符串中的百分号 (%) 符号处。该函数是逐步执行的。在第一个 % 符号中,插入 arg1,在第二个 % 符号处,插入 arg2,依此类推。

我在微信开放平台会看到如下代码

 代码如下 复制代码

$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
                $fromUsername = $postObj->FromUserName;
                $toUsername = $postObj->ToUserName;
                $keyword = trim($postObj->Content);
                $time = time();
    $msgType = "text";
                $textTpl = "
       
       
       %s
       
       
       0
       
";            
    if(!empty( $keyword ))
                {
                
                 $contentStr = $this->keyrep($keyword);
     if(  empty($contentStr) )
     {
      $contentStr ="你是故意的吧,没文化真可怕";//你是故意的吧,没文化真可怕;
     }
     //$contentStr = @iconv('UTF-8','gb2312',$keyword);
                 $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                 echo $resultStr;
     
                }else{
                 $contentStr = '没文化真可怕,居然不会打字!';//$this->keyrep($keyword);
                 //$contentStr = @iconv('UTF-8','gb2312',$keyword);
     $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                 echo $resultStr;
                }

上面用到的是xml中了,下面再看一个网友写的例子

 代码如下 复制代码


 /**
  *        sprintf()函数使用
  *        @date 2012-12-17
  *        @author cntnn11
  */
  /**
  *        手册定义:函数把格式化的字符串写写入一个变量中。
  *        他的可识别的格式
  *            %% - 返回百分比符号
  *            %b - 二进制数
  *            %c - 依照 ASCII 值的字符
  *            %d - 带符号十进制数
  *            %e - 科学计数法(比如 1.5e+3)
  *            %u - 无符号十进制数
  *            %f - 浮点数(local settings aware)
  *            %F - 浮点数(not local settings aware)
  *            %o - 八进制数
  *            %s - 字符串
  *            %x - 十六进制数(小写字母)
  *            %X - 十六进制数(大写字母)
  *        sprintf($str, arg1, arg2, arg3 ...);
 */
 
 /**
 *    1.    %%
 *        把%%替换成%
 */
 $testStr    = '测试下%%这个参数。会被替换成什么呢';
 echo sprintf($testStr),'
';
 //-> 测试下%这个参数。会被替换成什么呢;
 //只剩下一个%了
 //看来还真的只是返回一个‘%’。但是实际应用中该怎么用呢?
 //我也不知道~
 echo '



';
 /**
 *    2.    %b
 *        该参数只能替换整型数据。如果是浮点型,那么他只会取整数部分。小数点后边的会忽略
 *        如果是一个非整型数据,那么返回 0
 */
 $testStr    = '听说%b会替换成二进制数,真的吗?';
 $arg        = '10';
 echo sprintf($testStr, $arg),'
';
 //-> 1010;    $arg=10;    真的替换了!
 //-> 101;    $arg=4.5
 //-> 0;        $arg=str/bool...
 echo '


';
 
 /**
 *    3.    %c 返回字符编码的ASCII码
 *        TIP:[他不是返回ASCII码]
 *        $arg接受一个int传入即ASCII的数字值,然后返回该值对应的字符
 */
 $testStr    = '我们来测试下 %c : 试试看能返回ASCII码吗';
 $arg    = '122';
 echo sprintf($testStr, $arg);
 //-> A;    $arg=65;
 //-> z; $arg=122
 echo '


';
 /**
  *    4. %d 将一段字符里的%d替换成int型
  *        TIP:这里可以是任意一个int整型。
  *            如果是一个浮点数据,那么只会替换整数部分
  *            如果是非数字的,那么会替换成0
  */
 $testStr    = "这是一个ID,ID号是%d,";
 $arg        = '-4';
 echo sprintf($testStr, $arg);
 //-> 4;    $arg=4.5
 //-> 0; $arg=[a-zA-Zs];
 echo '


';
 
 /**
  *    5.    %e 科学计数法
  *        TIP:将一段很长很长的int整型数据以科学计数法的形式呈现
  *            同%d,该函数同样会忽略掉小数点后面的,任何非数值数据替换成0
 */
 $testStr    = "我很长,有N多位。。。 %e";
 $arg        = '46498464654864564642449463699789789313';
 echo sprintf($testStr, $arg);
 //-> 4.649846e+14;    $arg=464984646548645.64642449463699789789313
 //-> 0.000000e+0; $arg=asdfasdf;
 echo '


';
 
 /**
  *    5.    %u - 无符号十进制数
  *        不明白。。。如果有是负数,他的值不知道是啥值
 */
 $testStr    = "我是无符号的十进制数。。。 %u";
 $arg        = '456';
 echo sprintf($testStr, $arg);
 echo '


';
 
 /**
  *    6.    %f - 浮点数(local settings aware)
  *            难道和%d是相反的?
  *                这个会返回一个浮点数,并且小数点后面只有固定的6位
  *                字符串同样为 0 ;
 */
 $testStr    = "和那个d有啥区别呢?%f";
 $arg        = '456.235645';
 echo sprintf($testStr, $arg);
 echo '


';
 
 /**
  *    7.    %F - 浮点数(not local settings aware)
  *        难道和%f是相反的?怎么和小f没区别?不会吧
  */
 $testStr    = "和那个小写的f有啥区别呢?%F";
 $arg        = '12312316.46898';
 echo sprintf($testStr, $arg);
 echo '


';
 
 /**
  *    8.    %o - 八进制数
  *        同%d一样。只不过参数传入一个八进制数值
  */
 $testStr    = "将八进制数替换成十进制的 %o";
 $arg        = '8';
 echo sprintf($testStr, $arg);
 echo '


';
 
 /**
  *    9.    %x - 十六进制数(小写字母)
  *        同%d/%o一样。只不过参数传入一个小写字母的十六进制数值
  */
 $testStr    = "将十六进制数替换成十进制的 %o";
 $arg        = '456d12';
 echo sprintf($testStr, $arg);
 echo '


';
 
 /**
  *    10.    %X - 十六进制数(大写字母)
  *        同%d/%o/%x一样。只不过参数传入一个大写字母的十六进制数值
  *        貌似%x %X两个字母大小写没区别...
  */
 $testStr    = "将大写字母的十六进制数替换成十进制的 %o";
 $arg        = '456D12';
 echo sprintf($testStr, $arg);
 echo '


';
 
 /**
  *    11.    %s - 字符串
  *        用你传入的字符串替换掉%s
  */
 $string    = "这是用来测试的sprintf的字符串( %s )。今天消费了%f元。从西二旗到知春路有%d站。上班";
 $arg    = '';
 echo sprintf($string, $arg, 234, 10);
 echo '


';
 
 
  ?>
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1655
14
PHP Tutorial
1252
29
C# Tutorial
1226
24
PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

See all articles