Php string formatting functions

PHP sprintf() Function

Replace the percent (%) sign by a variable passed as an argument:

$number = 9;
$str = «Beijing»;
$txt = sprintf(«There are %u million bicycles in %s.»,$number,$str);
echo $txt;
?>

Definition and Usage

The sprintf() function writes a formatted string to a variable.

The arg1, arg2, ++ parameters will be inserted at percent (%) signs in the main string. This function works «step-by-step». At the first % sign, arg1 is inserted, at the second % sign, arg2 is inserted, etc.

Note: If there are more % signs than arguments, you must use placeholders. A placeholder is inserted after the % sign, and consists of the argument- number and «\$». See example two.

Syntax

Parameter Values

  • %% — Returns a percent sign
  • %b — Binary number
  • %c — The character according to the ASCII value
  • %d — Signed decimal number (negative, zero or positive)
  • %e — Scientific notation using a lowercase (e.g. 1.2e+2)
  • %E — Scientific notation using a uppercase (e.g. 1.2E+2)
  • %u — Unsigned decimal number (equal to or greater than zero)
  • %f — Floating-point number (local settings aware)
  • %F — Floating-point number (not local settings aware)
  • %g — shorter of %e and %f
  • %G — shorter of %E and %f
  • %o — Octal number
  • %s — String
  • %x — Hexadecimal number (lowercase letters)
  • %X — Hexadecimal number (uppercase letters)

Additional format values. These are placed between the % and the letter (example %.2f):

  • + (Forces both + and — in front of numbers. By default, only negative numbers are marked)
  • ‘ (Specifies what to use as padding. Default is space. Must be used together with the width specifier. Example: %’x20s (this uses «x» as padding)
  • — (Left-justifies the variable value)
  • 4 (Specifies the minimum width held of to the variable value)
  • .8 (Specifies the number of decimal digits or maximum string length)

Note: If multiple additional format values are used, they must be in the same order as above.

Technical Details

More Examples

Example

Example

$number = 123;
$txt = sprintf(«With 2 decimals: %1\$.2f

With no decimals: %1\$u»,$number);
echo $txt;
?>

Example

A demonstration of all possible format values:

$num1 = 123456789;
$num2 = -123456789;
$char = 50; // The ASCII Character 50 is 2

// Note: The format value «%%» returns a percent sign
echo sprintf(«%%b = %b»,$num1).»
«; // Binary number
echo sprintf(«%%c = %c»,$char).»
«; // The ASCII Character
echo sprintf(«%%d = %d»,$num1).»
«; // Signed decimal number
echo sprintf(«%%d = %d»,$num2).»
«; // Signed decimal number
echo sprintf(«%%e = %e»,$num1).»
«; // Scientific notation (lowercase)
echo sprintf(«%%E = %E»,$num1).»
«; // Scientific notation (uppercase)
echo sprintf(«%%u = %u»,$num1).»
«; // Unsigned decimal number (positive)
echo sprintf(«%%u = %u»,$num2).»
«; // Unsigned decimal number (negative)
echo sprintf(«%%f = %f»,$num1).»
«; // Floating-point number (local settings aware)
echo sprintf(«%%F = %F»,$num1).»
«; // Floating-point number (not local sett aware)
echo sprintf(«%%g = %g»,$num1).»
«; // Shorter of %e and %f
echo sprintf(«%%G = %G»,$num1).»
«; // Shorter of %E and %f
echo sprintf(«%%o = %o»,$num1).»
«; // Octal number
echo sprintf(«%%s = %s»,$num1).»
«; // String
echo sprintf(«%%x = %x»,$num1).»
«; // Hexadecimal number (lowercase)
echo sprintf(«%%X = %X»,$num1).»
«; // Hexadecimal number (uppercase)
echo sprintf(«%%+d = %+d»,$num1).»
«; // Sign specifier (positive)
echo sprintf(«%%+d = %+d»,$num2).»
«; // Sign specifier (negative)
?>

Читайте также:  Php замена строки между символами

Example

A demonstration of string specifiers:

Источник

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()

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:

  • 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

Читайте также:  Range xrange разница питон

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

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.

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:

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

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:

flags

  • Use + to prefix positive numbers with a plus sign +. By default, only the negative numbers are prefixed with a negative sign. See example:
  • 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:

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

‘; /*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:

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

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

Читайте также:  Парсинг характеристик товаров python

Example: Use 0 to fill the space:

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:

.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:

sprintf()

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:

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

'; $v = 0b10; //0b prefix represents a binary number $output = sprintf('%d', $v); echo $output; //2

Example: Convert decimal value in scientific notation

vprintf()

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

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

vsprintf()

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

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

sscanf()

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:

 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:

fscanf()

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

fprintf()

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

vfprintf()

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

Working with Strings:

Источник

Оцените статью