String Functions

PHP sprintf() Function

Topic: PHP String ReferencePrev|Next

Description

The sprintf() function returns a formatted string.

This function takes a special format string and then any number of other arguments, which will be formatted and spliced into the specified places in the format string to generate the result.

Related functions: fprintf(), printf(), vfprintf(), vprintf() and vsprintf().

The following table summarizes the technical details of this function.

Return Value: Returns the formatted string on success, or FALSE on failure.
Version: PHP 4+

Syntax

The basic syntax of the sprintf() function is given with:

sprintf(format, arg1, arg2, argN);

The following example shows the sprintf() function in action.

<?php
// Sample strings
$count = 50;
$country = "United States";
$format = "There are %d states in the %s.";

// Formatting and print the string
echo sprintf($format, $count, $country);
?>

Note: Every character in the format string will be printed literally, except the % character and characters that immediately follow it. The % character indicates the beginning of a conversion specification, which specifies how to print the arguments that follow the format string.

Tip: The sprintf() function is identical to printf() except that the printf() function outputs a text string directly, similar to the print and echo statements, whereas the sprintf() function returns the formatted string so that you can assign it to a variable.


Parameters

The sprintf() function accepts the following parameters.

Parameter Description
format Required. Specifies the format string. It is composed of ordinary characters (excluding %) and one or more conversion specifications.
arg1 Required. Specifies the argument to be formatted and inserted at the position of first conversion specification in the format string.
arg2 Optional. Specifies the argument to be formatted and inserted at the position of second conversion specification in the format string.
argN Optional. Specifies the argument to be formatted and inserted at the position of Nth conversion specification in the format string.

Conversion Specification Syntax

This section describes the syntax of conversion specification in the format string in detail.

A conversion specification begins with a percent symbol (%). You must include a conversion specification for each argument that is passed to the sprintf() function after the format string.

Alternatively, you can use the argument number followed by a dollar sign (i.e. argnum$) to apply multiple conversion specifications in the format string to the same argument. It must come immediately after the percent sign (%), before any other specifiers. See more examples section.

A conversion specification typically has the following syntax:

%[argnum$][flags][width][.precision]specifier

argnum

An integer followed by a dollar sign $, to specify which number argument to treat in the conversion.

flags

The flags consist of one or more of the following characters:

Flag Description
+ Adds a plus sign before positive numbers. By default, only negative numbers are marked.
- Left-justify within the given field width; Right justification is the default.
(space) Pads the result with spaces. This is the default.
0 Only left-pads numbers with zeros. With s specifiers this can also right-pad with zeros.
'(char) Pads the result with the character (char). Must be used together with the width specifier.

width

An integer that indicates how many characters (minimum) this conversion should result in.

precision

A period (.) followed by an integer who's meaning depends on the specifier:

  • For e, E, f and F specifiers: this is the number of digits to be printed after the decimal point (by default, this is 6).
  • For g and G specifiers: this is the maximum number of significant digits to be printed.
  • For s specifier: it acts as a cutoff point, setting a maximum character limit to the string.

If the period is specified without an explicit value for precision, 0 is assumed.

specifier

A single character indicating how the type of the argument should be interpreted.

specifier Description
% A literal percent character. No argument is required.
b The argument is treated as an integer and printed as a binary number.
c The argument is treated as an integer and printed as the character with that ASCII.
d The argument is treated as an integer and printed as a (signed) decimal number.
e The argument is treated as as scientific notation (e.g. 1.2e+2). The precision specifier stands for the number of digits after the decimal point.
E Like the e specifier but uses uppercase letter (e.g. 1.2E+2).
f The argument is treated as as a float and printed as a floating-point number (locale aware).
F The argument is treated as as a float and printed as a floating-point number (non-locale aware).
g General format. Uses e and f.
G Like the g specifier but uses E and f.
o The argument is treated as an integer and printed as an octal number.
s The argument is treated and printed as a string.
u The argument is treated as an integer and printed as an unsigned decimal number.
x The argument is treated as an integer and printed as a hexadecimal number (lowercase letters).
X The argument is treated as an integer and printed as a hexadecimal number (uppercase letters).

More Examples

Here're some more examples showing how sprintf() function actually works:

The following example shows how to apply multiple conversion specifications to the same argument.

<?php
// Sample string
$str = 'star';
$format = 'The polar %1$s is the brightest %1$s in the sky.';

// Formatting and print the string
echo sprintf($format, $str);
?>

Tip: If the format string is enclosed in double-quotes (""), you need to escape the dollar sign after argnum with a backslash character (\), like this %1\$s, so that the PHP doesn't try to interpret them as variable. Using a backslash like this is called an escape sequence.

The following example shows how to format the same number with and without decimal points.

<?php
// Sample string
$number = 499;
$format = "The number without decimal points: %1\$d, and the number with two decimal points: %1\$.2f";

// Formatting and print the string
echo sprintf($format, $number);
?>

By default, each conversion specification will be replaced by the formatted argument in the order they are listed inside the function. But, you can swap arguments inside the format string using argnum.

<?php
// Sample strings
$count = 50;
$country = "United States";
$format = "The %2\$s is a federal republic of %1\$d states.";

// Formatting and print the string
echo sprintf($format, $count, $country);
?>

Tip: If the order of the placeholders or conversion specifications in the format string does not match the order of the arguments listed inside the function. You can use argnum to easily indicate which arguments the placeholders refer to and leave the function code as is.

The following example demonstrates the use of various format specifiers for different types of data.

<?php
// Sample integers
$num1 = 123456789;
$num2 = -123456789;
$num3 = 65; // ASCII 65 is 'A'

// Notice the double %%, this simply prints a '%' character
echo sprintf("%%b = %b <br>",$num1); // Binary representation
echo sprintf("%%c = %c <br>",$num3); // The ASCII Character
echo sprintf("%%d = %d <br>",$num1); // Standard integer representation
echo sprintf("%%d = %d <br>",$num2); // Standard integer representation
echo sprintf("%%e = %e <br>",$num1); // Scientific notation (lowercase)
echo sprintf("%%E = %E <br>",$num1); // Scientific notation (uppercase)
echo sprintf("%%u = %u <br>",$num1); // Unsigned integer representation (positive)
echo sprintf("%%u = %u <br>",$num2); // Unsigned integer representation (negative)
echo sprintf("%%f = %f <br>",$num1); // Floating-point representation (locale aware)
echo sprintf("%%F = %F <br>",$num1); // Floating-point representation (non-locale aware)
echo sprintf("%%g = %g <br>",$num1); // Shorter of %e and %f
echo sprintf("%%G = %G <br>",$num1); // Shorter of %E and %f
echo sprintf("%%o = %o <br>",$num1); // Octal representation
echo sprintf("%%s = %s <br>",$num1); // String representation
echo sprintf("%%x = %x <br>",$num1); // Hexadecimal representation (lowercase)
echo sprintf("%%X = %X <br>",$num1); // Hexadecimal representation (uppercase)
echo sprintf("%%+d = %+d <br>",$num1); // Sign specifier (positive)
echo sprintf("%%+d = %+d <br>",$num2); // Sign specifier (negative)
?>

The following example shows how to format a string in different ways using s specifier.

<?php
$str1 = "Hello";
$str2 = "Hello Alexander!";

echo sprintf("[%s]<br>", $str1);     // Standard string output
echo sprintf("[%10s]<br>", $str1);   // Right-justifies the string with spaces
echo sprintf("[%-10s]<br>", $str1);  // Left-justifies the string value with spaces
echo sprintf("[%010s]<br>", $str1);  // Left-pads string with zeros.
echo sprintf("[%-010s]<br>", $str1); // Right-pads string with zeros
echo sprintf("[%'#10s]<br>", $str1); // Left-pads string with '#' character
echo sprintf("[%.10s]<br>", $str2);  // Cuts off string after 10 characters
?>
Bootstrap UI Design Templates Property Marvels - A Leading Real Estate Portal for Premium Properties