Categories
PHP

Formatting Strings

Earlier we presented the basic method for outputting text with echo and print, and the functions print_r( ) and var_dump( ), which can determine the contents of variables during debugging. PHP provides several other functions that allow more complex and controlled formatting of strings.

  1. printf()
    Accepts a string argument $format that describes how the remaining arguments $values are to be printed.
  2. sprintf()
    Works like printf(), but returns the string and does not print it.
  3. vprintf()
    Works like printf(), expects the $values for the placeholders in the string to be in the form of an array.
  4. vsprintf()
    A mixture of sprintf() and vprintf(): The placeholder values are provided in an array and the function returns the string but does not print it.
  5. sscanf()
    Parse a string and tries to match it with a pattern that contains placeholders.
  6. fscanf()
    Works similar to sscanf(), but it takes its input from a file.
  7. fprintf()
    Works similar to printf(), but it takes its input from a file.
  8. vfprintf()
    Works similar to vprintf(), but it takes its input from a file.

printf()

<?php
 //Syntax
 printf(string $format, mixed ...$values): int

This function applies formatting, whether to round doubles to a given number of decimal places, define alignment within a field, or display data according to different number systems.

Example: Truncate float

For example, a floating-point value such as 6.11111 might need to be truncated to 6.11:

<?php
 $v = 6.11111;
 printf ("The $v truncated to %.2f.", $v);
 //The 6.11111 truncated to 6.11.

The format string The $v truncated to %.2f. is the first parameter to the printf statement. Strings like The 6.11111 truncated to are output the same as with echo or print. The %.2f component is a conversion specification:

  • All conversion specifications begin with a % character.
  • The f indicates how the type of value should be interpreted. The f means the value should be interpreted as a floating-point number, for example, 6.11111 or 12.23. Other possibilities include b, c, d, and s, where b means binary, c means a single character, d means integer, and s means string.
  • The .2 is an optional width specifier. In this example, .2 means two decimal places, so the overall result of %.2f is that a floating-point number with two decimal places is output.

Example: The minimum characters this conversion should result in

<?php
 $v = 6.11111;
 printf ("The $v truncated to %10.2f.", $v);
 //The 6.11111 truncated to       6.11.

A specifier %10.2f means that the minimum width of the number before the decimal point should be ten (by default, the output is padded on the left with space characters and right-aligned), and two digits should occur after the decimal point (by default, the output on the right of the decimal point is padded on the right with zeros).

Example: format the output to have at least five digits by adding zeros to the left

<?php
 $v = 6.11111;
 printf ("The $v truncated to %05.2f.", $v);
 //The 6.11111 truncated to 06.11.

A specifier %05.2f means: % marks the start of conversion, 0 means “pad the string with zero” (by default, the output is padded on the left with space characters), .2 means two decimal places and the f means the argument ($v) is float.

Conversion Specifiers (Placeholders)

The format string (the first argument) may contain literal characters, escape sequences, and conversion specifiers. Escape sequences (e.g. \n for newline and \t for tab) in format will be converted to their respective characters.

Conversion specifiers, %s, %f, etc., are replaced by the corresponding argument. A conversion specification begins with a percent % symbol and defines how to treat the corresponding argument to printf() (or any corresponding function). The following table lists the conversions specifiers (placeholder):

Description
%bInteger value, binary representation is printed
%cInteger value, ASCII representation is printed
%dInteger value, signed decimal value is printed
%eDecimal value in scientific notation (1.2e+34)
%fFloat value, printed with respect to the locale settings
%FFloat value, printed without respect to the locale settings
%oInteger value, octal representation is printed
%sString value
%uInteger value, the unsigned decimal value is printed
%xInteger value, hexadecimal representation with lowercase letters is printed
%XInteger value, hexadecimal representation with uppercase letters is printed
Formatting String: List of Conversion Specifiers

You can include as many conversion specifications as you want within the string in the first argument, as long as you send an equivalent number of arguments to the function:

<?php
 $h = 'hello';
 $w = 'world';
 printf ('%s, %s', $h, $w);
 //hello, world

The %s specifier interprets its argument as a string. The following example demonstrates the usage of string and decimal specifiers:

<?php
 $city = 'Tokyo';
 $population = 37274000;
 printf ('%s has a population of %d', $city, $population);
 //Tokyo has a population of 37274000

Specifier Syntax

A conversion specification follows this prototype:
%[argnum$][flags][width][.precision]specifier

argnum$

Specifies which number argument to interpret in the conversion. By default, the first argument is treated first and then the second, and so on. By specifying the argument number (argnum$) you can choose a specific argument. 1$ represents the first argument, 2$ represents the second argument, and so on. See example:

<?php
 $a = 1;
 $b = 2;
 printf('%d, %d',$a,$b); //default
 // 1, 2
 
 printf('%2$d, %1$d',$a,$b);
 //2, 1

 printf('%2$d, %2$d', $a, $b);
 //2, 2

flags

  • Use + to prefix positive numbers with a plus sign +. By default, only the negative numbers are prefixed with a negative sign. See example:
<?php
 $a = -1;
 $b = 2;
 printf('%d, %d',$a,$b);
 // -1, 2

 printf('%+d, %+d',$a,$b);
 // -1, +2
  • Use - to left-align the result within the given field width. By default, the result aligned to right. See width examples.
  • Use space (default), 0, or a character to pad the result. See following padding examples under the width heading.

width

Set the minimum field width. In the following example, we provide 20 for the minimum result length, if the resulting length is smaller than the 20 characters, spaces are added to the result, see example:

<?php
 echo '<pre>';
 printf("%20s World\n", 'Hello');
 printf("%20s Hypertext Preprocessor\n", 'PHP');
 printf("%20s Hypertext Markup Language\n", 'HTML');
 printf("%20s JavaScript\n", "JS");
 printf("%20s Casecading Style Sheet\n", 'CSS');
 echo '</pre>';

/*Prints:
               Hello World
                 PHP Hypertext Preprocessor
                HTML Hypertext Markup Language
                  JS JavaScript
                 CSS Casecading Style Sheet
*/

Use - to left-align the result within the given field width. By default, the result aligned to right:

<?php
 echo '<pre>';
 printf("%-20s World\n", 'Hello');
 printf("%-20s Hypertext Preprocessor\n", 'PHP');
 printf("%-20s Hypertext Markup Language\n", 'HTML');
 printf("%-20s JavaScript\n", "JS");
 printf("%-20s Casecading Style Sheet\n", 'CSS');
 echo '</pre>';

/*Prints:
Hello                World
PHP                  Hypertext Preprocessor
HTML                 Hypertext Markup Language
JS                   JavaScript
CSS                  Casecading Style Sheet
*/

Example: Use 0 to fill the space:

<?php
 printf('%0-20sWorld', 'Hello');
 //Hello000000000000000World

 printf('%020sWorld', 'Hello');
 //000000000000000HelloWorld

Example: Use any character to fill the space (or pad the result)

You can specify any character other than a space or a zero in your padding specifier with a single quotation mark followed by the character you want to use. We used '- and '_ characters to pad result with - and _ in following exmaple:

<?php
 printf("%'--20sWorld\n", 'Hello');
 //Hello---------------World

 printf("%'_20sWorld", 'Hello');
 //_______________HelloWorld

.precision

Set the number of digits to be printed after the decimal point. Or, set the maximum character limit for a string. Use a period . followed by number., see example:

<?php
 $a = 1.0111;
 $b = 'hello, world';
 printf('%.2f, %.5s', $a, $b);
 //1.01, hello

sprintf()

<?php
 //Syntax
 sprintf(string $format, mixed ...$values): string

Unlike the printf() function which outputs the data to the browser, the sprintf() function returns a string that can be stored in a variable for later use. The following example uses sprintf() function to truncate a float to two decimal places, keeping the result in $output variable:

<?php
 $v = 6.11111;
 $output = sprintf ("The $v truncated to %.2f.", $v);

 echo $output;
 //The 6.11111 truncated to 6.11.

Example: Decimal to binary (and binary to decimal) conversion

<?php
 $v = 2;
 $output = sprintf ('%b', $v);
 echo $output; //10
 
 echo '<hr>';
 
 $v = 0b10; //0b prefix represents a binary number
 $output = sprintf('%d', $v);
 echo $output; //2

Example: Convert decimal value in scientific notation

<?php
 $v = 500000;
 $output = sprintf ('%e', $v);
 echo $output; //5.000000e+5
 
 //Output capital E
 $output = sprintf ('%E', $v);
 echo $output; //5.000000E+5
 
 //Truncate decimal point
 $output = sprintf ('%.2E', $v);
 echo $output; //5.00E+5

vprintf()

<?php
 //Syntax
 vprintf(string $format, array $values): int

This function works similar to printf() but accepts an array of arguments, rather than a variable number of arguments. See following example:

<?php
 $array = ['city'=>'Tokyo','population'=>37274000];
 vprintf ('%s has a population of %d', $array);
 //Tokyo has a population of 37274000

vsprintf()

<?php
 //Syntax
 vsprintf(string $format, array $values): string

In this example, we use vsprintf() function, which works as sprintf() but accepts an array of arguments:

<?php
 $array = ['city'=>'Tokyo','population'=>37274000];
 $result = vsprintf ('%s has a population of %d', $array);
 
 echo $result;
 //Tokyo has a population of 37274000

sscanf()

<?php
 //Syntax
 sscanf(string $input, string $format, mixed &...$vars): array|int|null

This function parses a string and tries to match it with a pattern that contains placeholders.

In following example, the $date string contains a date and is scanned using the string '%d/%d/%d' with several placeholders. The function returns an array with all values for the matched placeholders. Then this array is passed to vprintf() to print it:

<?php
 $date = '06/01/22';
 $values = sscanf($date, '%d/%d/%d');

 print_r($values);
 //Array ( [0] => 6 [1] => 1 [2] => 22 

 vprintf('Month: %d; Day: %d; Year: %d.', $values);
 //Month: 6; Day: 1; Year: 22.

Alternatively, you can provide a list of variable names as additional parameters to sscanf(). Then the function writes the substrings that match the placeholders into these variables, see following code:

<?php
  $date = '02/01/22';
  $values = sscanf($date, '%d/%d/%d', $m, $d, $y);
  echo "Month: $m; Day: $d; Year: $y.";

fscanf()

<?php
 //Syntax
 fscanf(resource $stream, string $format, mixed &...$vars): array|int|false|null

Works similar to sscanf(), but it takes its input from a file (created using fopen()).

fprintf()

<?php
 //Syntax
 fprintf(resource $stream, string $format, mixed ...$values): int

Works similar to printf(), but it takes its input from a file (created using fopen()).

vfprintf()

<?php
 //Syntax
 vfprintf(resource $stream, string $format, array $values): int

Works similar to vprintf(), but it takes its input from a file (created using fopen()).


Working with Strings: