Php printf examples. Sprintf - Returns a formatted string

(PHP 4, PHP 5, PHP 7)

sprintf - Returns a formatted string

List of parameters

A format string consists of zero or more directives: ordinary characters (except % ), which are copied directly into the resulting string, and transformation descriptors, each of which is replaced by one of the parameters. This applies to both sprintf(), and to printf().

Each conversion specifier consists of a percent sign ( % ), followed by one or more additional elements (in the order they are listed here):

  1. Optional character descriptor, indicating how the sign (- or +) will be applied to the number. By default, only the minus sign is used if the number is negative. This specifier causes positive numbers to also display a plus sign and was added in PHP 4.3.0.
  2. Optional padding specifier, which specifies which character will be used to pad the result to the required length. It could be a space or 0 . The default is space. An alternate character can be specified using a single quote ( " ). See examples below.
  3. Optional alignment descriptor, which specifies left or right alignment. By default it is aligned to the right, - used for left alignment.
  4. Optional number width specifier, which specifies the minimum number of characters that the result of this conversion will contain.
  5. Optional precision descriptor, specified as a period (".") followed by an optional decimal string that specifies how many decimal places to display for floating-point numbers. When used with strings, this specifier acts as a cutting point that sets the maximum character limit. You can also specify the symbol used to complete the number between the dot and the number.
  6. Type specifier, which specifies how to treat the argument's data type. Valid types:

    • % - percentage symbol. The argument is not used.
    • b- the argument is treated as an integer and output as a binary number.
    • c- the argument is treated as an integer and output as a character with the corresponding ASCII code.
    • d- the argument is treated as an integer and output as a signed decimal number.
    • e- the argument is interpreted as a number in scientific notation (for example, 1.2e+2). The precision specifier indicates the number of decimal places since PHP 5.2.1. In earlier versions, it indicated the number of significant figures (one less sign).
    • E- similar %e, but uses a capital letter (for example, 1.2E+2).
    • f- the argument is treated as a floating point number and is also output depending on the locale.
    • F- the argument is treated as a floating point number and is also output, but without depending on the locale. Available starting from PHP 4.3.10 and PHP 5.0.3.
    • g %e And %f.
    • G- selects the shortest entry from %E And %f.
    • o- the argument is treated as an integer and output as an octal number.
    • s- the argument is treated as a string.
    • u- the argument is treated as an integer and output as an unsigned decimal number.
    • x- the argument is treated as an integer and output as a hexadecimal number (lowercase).
    • X- the argument is treated as an integer and output as a hexadecimal number (in uppercase).

The variables will be converted to the appropriate type for the specifier:

Type Handling
Type Specifier
string s
integer d, u, c, o, x, X, b
double g, G, e, E, f, F

Attention

Trying to use a combination of strings and width specifiers with encodings that require more than one byte per character may produce unexpected results.

The format string supports numbering and reordering of parameters. For example:

Example #1 Changing the order of parameters

$num = 5 ;
$location = "tree" ;

$format = "%d monkeys are sitting on %s";

?>

This code will output "5 monkeys sitting on a tree". Now imagine that the format string is contained in a separate file, which will then be translated into another language, and we rewrite it like this:

Example #2 Changing the order of parameters

$format = "There are %d monkeys sitting on %s";
echo sprintf ($format, $num, $location);
?>

There is a problem: the order of the conversion specifiers does not match the order of the arguments. We don't want to change the code, and we need to specify which argument corresponds to which conversion specifier.

Example #3 Changing the order of parameters

$format = "There are %1$d monkeys sitting on %2$s";
echo sprintf ($format, $num, $location);
?>

Argument numbering has another use: it allows you to print the same argument multiple times without passing additional parameters to the function.

Example #4 Changing the order of parameters

$format = "There are %1$d monkeys sitting on %2$s.
It's great to have %2$s sitting on %1$d monkeys."
;
echo sprintf ($format, $num, $location);
?>

When changing the order of parameters position descriptor n$ must come immediately after the percent sign ( % ) before all other descriptors, as shown in the example below.

Example #5 Specifying a complement character

echo sprintf ("%".9d\n" , 123 );
echo sprintf ("%".09d\n" , 123 );
?>

123 000000123

Example #6 Using the position specifier and in conjunction with other descriptors

$format = "There are %1$04d monkeys sitting on %2$s";
echo sprintf ($format, $num, $location);
?>

The result of running this example:

0005 monkeys sitting on a tree

Comment:

An attempt was made to use a position specifier greater than PHP_INT_MAX, will cause the function to generate a warning sprintf() .

Attention

The c type specifier ignores padding and width

Return values

Returns a string formatted according to format .

Examples

Example #7 sprintf(): padding with zeros

$n = 43951789 ;
$u = - 43951789 ;
$c = 65 ; // ASCII 65 is "A"

// note that double %% is output as single "%"
printf ("%%b = "%b"\n" , $n ); // binary representation
printf ("%%c = "%c"\n" , $c ); // prints an ascii character, similar to the chr() function
printf ("%%d = "%d"\n" , $n ); // regular integer
printf ("%%e = "%e"\n" , $n ); // scientific notation
printf ("%%u = "%u"\n" , $n ); // unsigned integer representation of a positive number
printf ("%%u = "%u"\n" , $u ); // unsigned integer representation of a negative number
printf ("%%f = "%f"\n" , $n ); // representation of a floating point number
printf ("%%o = "%o"\n" , $n ); // octal representation
printf ("%%s = "%s"\n" , $n ); // line
printf ("%%x = "%x"\n" , $n ); // hexadecimal representation (lower case)
printf ("%%X = "%X"\n" , $n ); // hexadecimal representation (upper case)

Printf ("%%+d = "%+d"\n" , $n ); // sign descriptor with a positive integer
printf ("%%+d = "%+d"\n" , $u ); // sign descriptor with a negative integer
?>

The result of running this example:

%b = "10100111101010011010101101" %c = "A" %d = "43951789" %e = "4.39518e+7" %u = "43951789" %u = "4251015507" %f = "43951789.000000" %o = "247523 255 " %s = "43951789" %x = "29ea6ad" %X = "29EA6AD" %+d = "+43951789" %+d = "-43951789"

Example #8 printf(): string descriptors

$s = "monkey" ;
$t = "many monkeys" ;

Printf("[%s]\n" , $s ); // normal line output
printf ("[%10s]\n" , $s ); // right align with spaces
printf ("[%-10s]\n" , $s ); // left alignment with spaces
printf ("[%010s]\n" , $s ); // zero padding also works with strings
printf ("[%"#10s]\n" , $s ); // use your own complementary "#" character
printf ("[%10.10s]\n" , $t ); // left alignment with 10 character trim
?>

The PHP sprintf function allows you to convert and fit a number of arguments into a single character string. Formatting specifiers allow you to work with characters, strings, integers, and real numbers.

The function is used for formatting tabular information and creating templates. It can be used for preliminary formalization of source data in a certain structure, changing their content or sequence.

PHP sprintf() function syntax

The result of the function is a string of characters formed in a certain sequence from specific data, function parameters:

  • format string;
  • list of arguments.

For formatting, you can use any design and logic, including HTML tags. Although there are no restrictions on the use of sprintf, the PHP manual defines conversion specifiers more towards numeric information.

The format element begins with a % character and ends with a qualifier character. Most of the formatting capabilities lie in the area of ​​numeric information. The ability to convert a number to binary and hexadecimal formats is very practical. Here the sprintf function in PHP is hardly worth writing a replacement for.

The example above highlights the rules for naming arguments and distinguishing the specifier x from X. The correct use of references to the sequence of arguments that are formatted is important for the correct result. Numbering always starts from 1.

The order in which the links are used does not matter, but it is important to remember: the PHP function sprintf considers all % elements (without specifying the argument number) sequentially in the general list. Neither the number nor the sequence of % elements specified with specific parameter numbers has anything to do with the numbering of the general list.

Description of an example of using sprintf in PHP

If it is not directly possible to manage the argument as a string, then managing the format string and outputting digital information to the result string is not a problem.

In the first two lines of the example (output of arguments Arg1, Arg2c and Arg2p), the first argument - the string (position name) is output as is. The third argument takes up 12 (14) characters in the output. The first line justifies the number on the left with zeros for a total length of 12 characters. There are four characters after the dot. The second line justifies the number to the right (the fractional part) to 14 characters. A sign that you need to align to the right is the - symbol.

The format string is a regular string of characters. You can insert calculated expressions into it. In this case, insertions ($cL) and ($cR) are used to highlight another number. This made the format string clearer and easier to write in all examples.

Generating a format string

The work of PHP in Russian, or the sprintf function, is the work of the interpreter in a natural and convenient environment. Actually, an HTML page with PHP code inserts represents any context in any language. This is not the freedom that JavaScript provides in a browser environment.

To output Russian content in PHP, you don't need to encode Cyrillic, but sometimes you have to use the iconv() conversion function. In any case, everything is accessible and readable.

The text for inserting PHP code into an HTML page is clear and relevant. Usage in character string:

Variable value ABC=($ABC) units

The insert ($ABC) only matters once and is executed only once.

Features of executing PHP code on a page

Interpreter just once views the page and just once replaces inserts ($ABC) with their values. The programmer may, at his discretion, use the phrase "just once" forcing PHP to repeatedly approach the desired result.

In any case, once the HTML page is sent to the browser, there is no PHP code in it.

If a page element from the browser initiates contact with the server, it can launch a new PHP script. Here the insertions ($ABC) are very relative and there is no guarantee of the correct result. But the use of sprintf in PHP is the dynamics of such a possibility.

The developer can not only get the desired execution of such an insertion, but also change the line to which it will transfer the desired value.

Moment of content formation

Using the potential of PHP as a means of generating inserts into an HTML page, as a tool for generating the entire page, is natural. This is where the site begins. As soon as the page is formed, and a visitor actually comes to the site, then according to modern ideas:

  • the page cannot be changed;
  • miss the user Same it is forbidden.

In fact, the visitor came to the site and received the first response in the form of HTML code. It is completely wrong to change this answer - it means telling the visitor that the page is changing it. But the page must respond to the visitor’s actions adequately and on his initiative.

The arrival of a visitor is the first response. The visitor action is an adequate reaction of the page and its preparation for all the expected next actions of the visitor.

A significant share of responsibility for the dynamics of the page at the visitor's initiative falls on JavaScript, but it functions only in the browser, and can only send AJAX requests to the server. Each call to the server can launch a PHP script. But the moment of page formation and the moment of response to a request differ significantly.

The PHP sprintf function is an ideal tool for dynamically generating a response template and filling it with the desired value.

Changing PHP code at runtime

The idea of ​​code dynamics was born along with the first programming language and today is present in every modern programming language.

Executing code via eval (line of code) is considered a security hole today, but it is as popular as it is dangerous.

To change code at runtime, you don't need to use the eval() function today. This is more of a quick breakfast, the execution of one or two commands, rather than a practical foundation for building the desired dynamics.

The PHP sprintf() function allows you to design a script template, for example, an object code that will be called when a particular visitor action occurs. The established practice of recording the bodies of objects in the form of independent files is an ideal solution for changing them during the operation of the site.

Using tools that complement the functionality of sprintf() allows you not only to change the objects used as a result of the actions of a particular visitor, but also to transfer this dynamics to work with other visitors: this is the development of the site, the dynamics of its functionality, the accumulation of work experience and knowledge.

For formatted output in PHP Two great features are used: printf() And sprintf(). They have quite a lot of capabilities, which we will discuss in this article.

I’ll say right away that the difference between printf() And sprintf() only that the first one outputs the string directly to the output stream (for example, to the browser), and the second one returns it.

A function parameter is a string that has characters with %, called specifiers, And characters without %, called directives. Directives remain unchanged when formatted, but the specifier leads to the substitution of other function parameters (following the format line).

There are several specifiers that are combined into one group (one common % ), the order of which is as follows:

  1. Padding specifier. Allows you to fill a string to a specified size with a specific character. By default, this character is a space.
  2. Alignment specifier. This specifier allows you to set the line alignment to the right (by default), or to the left (if you specify " - ").
  3. Minimum width specifier. If the result has a shorter string length, it will be filled with characters from the padding specifier to the specified width.
  4. Precision specifier. Allows you to specify how many decimal places to leave for a floating point number.
  5. Type specifier. This specifier specifies the type of data to be output. There are 8 of them, but in practice the following are used:
    • d- an integer in decimal form.
    • f- a floating point number in decimal form.
    • s- line.

Let's look at the classic example for outputting a formatted date:

$year = 2012;
$month = 9;
$day = 28;
printf("Date of writing: %02d.%02d.%04d", $day, $month, $year);
?>

It is not difficult to guess that the result will be the following line: " Date of article writing: 09/28/2012". Please note how many groups of specifiers, as many parameters are transmitted in addition to the format itself. String " Date of article writing:" is a directive, and it remains unchanged. Now let's look at the second group of specifiers, which is responsible for the month, as an example. The other groups are absolutely identical.

  • %
  • 0 - a character with which the specified parameter will be filled to the required width.
  • 2 - minimum width. Accordingly, if the length of the line is less, it will be filled 0 .
  • d- will be output as an integer. If you put, for example, b(another type specifier), then the same number will be displayed, but in binary form.

I’ll give you another popular one example of using the printf function (and sprintf()) associated with rounding numbers:

$x = 12.596123;
printf("%06.2f", $x); // "012.60" will be displayed
?>

Let's look at the first argument of the function printf():

  • % - the beginning of the specifier group.
  • 0 - character to fill to the required length.
  • 6 - required length (the point is, of course, also included in this length).
  • .2 - accuracy up to 2 decimal places.
  • f- type of floating point numbers. Actually, rounding makes sense only for this type.

As you can see, printf() and sprintf() functions make it easy to solve seemingly complex problems. Therefore, you definitely need to have them in your arsenal.

string sprintf(string format [, mixed args])

Returns a string created using the format string format.

The format string consists of directives: regular characters (except %), which are copied into the result string, and transformation descriptors , each of which is replaced by one of the parameters. This also applies to fprintf() , sprintf() And printf() .

Each conversion specifier consists of a percent sign (%) followed by one or more additional elements (in the order they are listed here):

    Optional padding specifier , which specifies which character will be used to pad the result to the required length. This can be a space or 0. The default is space. An alternative character can be specified with " . See examples below.

    Optional alignment descriptor , which determines alignment to the left or right. By default it is aligned to the right, - used for alignment to the left.

    Optional number width specifier , which specifies the minimum number of characters that the result of this conversion will contain.

    Optional precision descriptor , which specifies how many decimal places to display for floating-point numbers. Only meaningful for numeric data type float. (To format numbers it is also convenient to use the function number_format() .)

  1. Type specifier , which specifies how to treat the argument's data type. Valid types:

    % is the percent symbol. The argument is not used.
    b - the argument is treated as an integer and output as a binary number.
    c - the argument is treated as an integer and output as a character with the corresponding ASCII code.
    d - the argument is treated as an integer and is output as a signed decimal number.
    e - the argument is interpreted as float and is output in scientific notation (for example 1.2e+2).
    u - the argument is treated as an integer and is output as an unsigned decimal number.
    f - the argument is interpreted as float and is output as a decimal floating point number.
    o - the argument is treated as an integer and output as an octal number.
    s - the argument is treated as a string.
    x - the argument is treated as an integer and is output as a hexadecimal number (in lowercase letters).
    X - the argument is treated as an integer and is output as a hexadecimal number (in upper case letters).

Since PHP 4.0.6, the format string supports numbering and reordering of parameters. For example:


This code will output "There are 5 monkeys in the tree". Now imagine that the format string is contained in a separate file, which will then be translated into another language, and we rewrite it like this:

Example 2: Changing the order of parameters

$format = "The %s contains %d monkeys" ;

?>
There is a problem: the order of the conversion specifiers does not match the order of the arguments. We don't want to change the code, and we need to specify which argument corresponds to which conversion specifier.

Example 3: Changing the order of parameters

$format = "The %2\$s contains %1\$d monkeys";
printf ($format, $num, $location);
?>
Argument numbering has another use: it allows you to print the same argument several times without passing additional parameters to the function.