Manuel PHP
Précédent   Suivant

sprintf

sprintf -- Retourne une chaîne formatée

Description

sprintf(string format, mixed [args]...);

Retourne une chaîne formatée avec le format format.

La chaîne de formet est composée de 0 ou plus directives : généralement des caractères qui sont recopiés tels quel (hormis %), et des spécifications, chacune d’elle disposant de son propre paramètre. Cela s’applique à sprintf() et printf()

Chaque conversion consistent dans l’ordre :

  1. Une option de remplissage, qui indique quel caractère sera utilisé pour le remplissage, et la taille finale de la chaîne. Le caractère de remplissage peut être un espace ou le caractère zéro.
  2. An optional padding specifier that says what character will be used for padding the results to the right string size. This may be a space character or a 0 (zero character). The default is to pad with spaces. An alternate padding character can be specified by prefixing it with a single quote ('). See the examples below.
  3. An optional alignment specifier that says if the result should be left-justified or right-justified. The default is right-justified; a - character here will make it left-justified.
  4. An optional number, a width specifier that says how many characters (minimum) this conversion should result in.
  5. An optional precision specifier that says how many decimal digits should be displayed for floating-point numbers. This option has no effect for other types than double. (Another function useful for formatting numbers is number_format().)
  6. A type specifier that says what type the argument data should be treated as. Possible types:

% - a literal percent character. No argument is required.
b - the argument is treated as an integer, and presented as a binary number.
c - the argument is treated as an integer, and presented as the character with that ASCII value.
d - the argument is treated as an integer, and presented as a decimal number.
f - the argument is treated as a double, and presented as a floating-point number.
o - the argument is treated as an integer, and presented as an octal number.
s - the argument is treated as and presented as a string.
x - the argument is treated as an integer and presented as a hexadecimal number (with lowercase letters).
X - the argument is treated as an integer and presented as a hexadecimal number (with uppercase letters).

See also: printf(), number_format()

Examples

Example 1. sprintf: zero-padded integers
$isodate = sprintf("%04d-%02d-%02d", $year, $month, $day);
Example 2. sprintf: formatting currency
$money1 = 68.75;
$money2 = 54.35;
$money = $money1 + $money2;
// echo $money will output "123.1";
$formatted = sprintf ("%01.2f", $money);
// echo $formatted will output "123.10"

Précédent Sommaire Suivant
soundex Chapitre strchr