Web студия "GrandView"
  Главная   Написать Контакты
   
   
О проекте
Руководство php
 

sprintf

(PHP 3, PHP 4, PHP 5)

sprintf -- Возвращает отформатированную строку

Описание

string sprintf ( string format [, mixed args] )

Возвращает строку, созданную с использованием строки формата format.

Строка формата состоит из директив: обычных символов (за исключением %), которые копируются в результирующую строку, и описатели преобразований, каждый из которых заменяется на один из параметров. Это относится также к fprintf(), sprintf() и printf().

Каждый описатель прреобразований состоит из знака процента (%), за которым следует один или более дополнительных элементов (в том порядке, в котором они здесь перечислены):

  1. Необязательный описатель заполнения, который определяет, какой символ будет использоваться для дополнения результата до необходимой длины. Это может быть пробел или 0. По умолчанию используется пробел. Альтернативный символ может быть указан с помощью '. См. примеры ниже.

  2. Необязательный описатель выравнивания, определяющий выранивание влево или вправо. По умолчанию выравнивается вправо, - используется для выравнивания влево.

  3. Необязательное число, описатель ширины, определяющий минимальное число символов, которое будет содержать результат этого преобразования.

  4. Необязательный описатель точности, определяющий, сколько десятичных разрядов отображать для чисел с плавающей точкой. Имеет смысл только для числовых данных типа float. (Для форматирования чисел удобно также использовать функцию number_format().)

  5. Описатель типа, определяющий, как трактовать тип данных аргумента. Допустимые типы:

    % - символ процента. Аргумент не используется.
    b - аргумент трактуется как целое и выводится в виде двоичного числа.
    c - аргумент трактуется как целое и выводится в виде символа с соответствующим кодом ASCII.
    d - аргумент трактуется как целое и выводится в виде десятичного числа со знаком.
    e - аргумент трактуется как float и выводится в научной нотации (например 1.2e+2).
    u - аргумент трактуется как целое и выводится в виде десятичного числа без знака.
    f - аргумент трактуется как float и выводится в виде десятичного числа с плавающей точкой.
    o - аргумент трактуется как целое и выводится в виде восьмеричного числа.
    s - аргумент трактуется как строка.
    x - аргумент трактуется как целое и выводится в виде шестнадцатиричного числа (в нижнем регистре букв).
    X - аргумент трактуется как целое и выводится в виде шестнадцатиричного числа (в верхнем регистре букв).

Начиная с PHP 4.0.6 в строке формата поддерживается нумерация и изменение порядка параметров. Например:

Пример 1. Изменение порядка параметров

<?php
$format
= "There are %d monkeys in the %s";
printf($format, $num, $location);
?>
Этот код выведет "There are 5 monkeys in the tree". Теперь представьте, что строка формата содержится в отдельном файле, который потом будет переведен на другой язык, и мы переписываем ее в таком виде:

Пример 2. Изменение порядка параметров

<?php
$format
= "The %s contains %d monkeys";
printf($format, $num, $location);
?>
Появляется проблема: порядок описателей преобразования не соответствует порядку аргументов. Мы не хотим менять код, и нам нужно указать, какому аргументу соответствует тот или иной описатель преобразования.

Пример 3. Изменение порядка параметров

<?php
$format
= "The %2\$s contains %1\$d monkeys";
printf($format, $num, $location);
?>
Нумерация аргументов имеет еще одно применение: она позволят вывести один и тот же аргумент несколько раз без передачи функции дополнительных параметров.

Пример 4. Изменение порядка параметров

<?php
$format
= "The %2\$s contains %1\$d monkeys.
           That's a nice %2\$s full of %1\$d monkeys."
;
printf($format, $num, $location);
?>

См. также описание функций printf(), sscanf(), fscanf(), vsprintf() и number_format().

Примеры

Пример 5. sprintf(): заполнение нулями

<?php
$isodate
= sprintf("%04d-%02d-%02d", $year, $month, $day);
?>

Пример 6. sprintf(): форматирование денежных величин

<?php
$money1
= 68.75;
$money2 = 54.35;
$money = $money1 + $money2;
// echo $money выведет "123.1";
$formatted = sprintf("%01.2f", $money);
// echo $formatted выведет "123.10"
?>

Пример 7. sprintf(): научная нотация

<?php
$number
= 362525200;

echo
sprintf("%.3e", $number); // выведет 3.63e+8
?>



sscanf> <soundex
Last updated: Sat, 27 Jan 2007
 
add a note add a note User Contributed Notes
sprintf
me at umarfarooq dot net
06-Sep-2007 11:29
/**
This function returns a formated  string with the legnth you specify
@string holds the string which you want to format
@len holds the length you want to format
**/
function formatString($string, $len)
{
    if (strlen($string) < $len)
    {
        $addchar=($len - strlen($string)) ;
        for ($i = 0; $i < $addchar; $i++)
        {
            $string=sprintf("$string%s", "0");
        }
    }
   
    if (strlen($string) > $len)
    {
        $string=substr($string,0,$len);
    }
   
    return $string;   
}
Thomas Breuss
11-May-2007 12:03
Note:
If you want to use % in sprintf, you have to "quote" it like %%.

Example:
echo sprintf("Green => %d%%'", 50);

Output:
Green => 50%
eagle at electric-force dot net
28-Mar-2007 12:25
Display an binary string like an Hex Editor.

<?php
function BinToHexView($binstr) {
   
$HexView = "";

   
$binpos = 0;
   
$binsize = strlen($binstr);
   
$binr = ( ($binsize-$binpos-16) > 16 ? 16 : $binsize-$binpos-16 );

    while (
$binr > 0) {
       
$hline = "";
       
$dline = "";
       
$HexView .= sprintf("%04x", $binpos);
        for (
$c=0;$c<$binr;$c++) {
           
$hline .= sprintf("%02x",ord($binstr[$binpos+$c]))." ";
        }
        for (
$c=0;$c<$binr;$c++) {
           
$ord = ord($binstr[$binpos+$c]);
           
$dline .= ( $ord<32 || $ord>126 ? "." : $binstr[$binpos+$c] );
        }
       
$HexView .= sprintf("  %-48s  %-16s\n", $hline, $dline);
       
$binpos += $binr;
       
$binr = ( ($binsize-$binpos-16) > 16 ? 16 : $binsize-$binpos-16 );
    }

    return
$HexView;
}
?>
29-Jan-2007 10:15
In response to juan at ecogomera dot com:

I think what you want is:

$x = 3327
$y=decbin($x);
echo $y."<br>";
$z = sprintf("%012d", $x);
echo $z;

3327
110011111111
000000003327

Right? You were double-converting the number. First to binary, then again to decimal. You should be converting the source number directly into the required base.
SWestrup
09-Nov-2006 11:46
In response to Anonymous, who claimed that:

  printf("[%s]\n", str_pad('Hello', 20));

and

  printf("[%-20s]\n", 'Hello');

are the same thing: you've missed the point.

They're only the same when the amount of padding is a known constant. When its a variable (or an expression), its often much more convenient to be able to write:

  printf("[%-*s]\n", 3*$n+2, "Hello");

than what you have to go through now, which is either:

  $t = 3*$n+2;
  printf("[%-{$t}s]\n","Hello");

or

  printf("[%s]\n", str_pad('Hello', 3*$n+2));
Anonymous
16-Oct-2006 04:04
In response to Fredrik Rambris in the com top domain:

<?php

//Your code:

printf("[%s]\n", str_pad('Hello', 20));

//Is the same as:

printf("[%-20s]\n", 'Hello');

?>
Fredrik Rambris in the com top domain
28-Sep-2006 02:48
The C implementation of printf (alteast in glibc) can handle field length as arguments like this:

printf("[%-*s]\n", (int)20, "Hello");

To have the same result in PHP you need to run

printf("[%s]\n, str_pad("Hello", 20) );

It would be nice if one could use the field length directly like in C.
Moore (at) Hs-Furtwangen (dot) De
12-Aug-2006 11:54
Here a litle function that might come handy one time:
It gives back a String and adds a <BR> (you can change it to <br />) to every line end. And it adds $num blanks to the front of the next line.

<?php
 
function nl2brnl($text, $num)
  {
   return
preg_replace("/\\r\\n|\\n|\\r/", sprintf("% -".(5+$num)."s","<BR>\\n"), $text);
  }

$a = " one\\n two\\r\\n three";

$b = nl2brnl($a, 2);

var_dump($b);

/* output will be:
string(30) " one<BR>
   two<BR>
   three"
*/

echo "  <P>\\n   ";
echo
$b

/* output will be:
  <P>
   one<BR>
   two<BR>
   three
*/
?>

Is helpfull for avouding code_soup.
bknakkerNO at SPAMgmail dot com
10-Aug-2006 02:54
Note that in PHP5 (.1.4 for me) sprintf will not use the __toString function of an object.

<?php
class pr{
private
$l;
public function
__construct($l)
{
$this->l=$l;
}
public function
__toString()
{
return
$this->l;
}
}
echo new
pr('This works!!'); //This will display 'This works!!'
echo sprintf(new pr('This doesnt')); // will display 'Object'
?>

Be careful with that!
Ulf Wostner
06-Aug-2006 10:35
<?php
#-----------------------------------------------------
# Viewing Two's Complement using sprintf formatting.
#-----------------------------------------------------
# Systems using Two's Complements have exactly one number that equals its own Two's Complement.
# On a 32-bit system look at  1000 0000 0000 0000  for  -2147483648
# Take the one's complement, to get 0111 1111 1111 1111, add 1
# to get the Two's Complement: 1000 0000 0000 0000
#  We are back to the original number, the so-called Weird Number for 32-bits.

# For a 64-bit system, format that number as binary, width 64, padded with 0's.

printf("%064b\n", -2147483648);

# Output with added spaces:
# 11111111 11111111 11111111 11111111 10000000 00000000 00000000 00000000

# And here is the Two's Complement on a 64-bit system.

printf("%064b\n", +2147483648);

# Output with added spaces:
# 00000000 00000000 00000000 00000000 10000000 00000000 00000000 00000000
# They share those last 32 bits, accounting for the 32-bit Weird Number.

#----------------------------------------------------------
# Is PHP running  32-bit or 64-bit?
#----------------------------------------------------------
# Sure, we can look at the max int, but  The Weird Number  also tells if we are in 32-bit, 64-bit, or ...

function getBitCount() {
 
$how_many_bits = 1$n = 2;
  while(
True) {
   
$how_many_bits += 1;   $n *= 2# powers of 2
    # matches its own two's complement? 
   
if( sprintf("%b", $n) == sprintf("%b", -$n)  )
      return
1 + $how_many_bits;
  }
  return;
}
?>
egingell at sisna dot com
26-Apr-2006 01:51
<?
/**
 * [string or int] vprint ( string $format [, mixed $ary [, bool $return]] )
 *
 * Closely mimics the functionality of sprintf(), printf(), vprintf(), and vsprintf().
 *
 * Replaces %[bcdeufFosxX] with each element of $ary
 *     See http://us3.php.net/manual/en/function.sprintf.php for details on replacement types.
 *
 * If there are not enough elements in $ary (or it is left out) to satisfy $format,
 *     it will be padded to the correct length.
 *
 * Since v*printf() doesn't mind having too many elements in the array, $format will be left alone.
 *
 * If $ary is a string, it will be recast into an array.
 *
 * If $return is set to a value considered to be false (0, '', null, false, and array()),
 *     then the output will be sent to STDOUT and the strlen() of the output string will be returned;
 *     otherwise, the output string will be returned.
 *
 * It's buggy when using the argument swapping functionality, unless you do it propperly.
 *
 * May break when using modifiers (%.4e, %02s, etc), unless you do it propperly.
 **/
function vprint($format, $ary = array(), $return = true) {
    // Sanity?!
    if (!is_array($ary)) $ary = array($ary);

    // Find %n$n.
    preg_match_all('#\\%[\\d]*\\$[bcdeufFosxX]#', $format, $matches);

    // Weed out the dupes and count how many there are.
    $counts = count(array_unique($matches[0]));

    // Count the number of %n's and add it to the number of %n$n's.
    $countf = preg_match_all('#\\%[bcdeufFosxX]#', $format, $matches) + $counts;

    // Count the number of replacements.
    $counta = count($ary);

    if ($countf > $counta) {
        // Pad $ary if there's not enough elements.
        $ary = array_pad($ary, $countf, "&nbsp;");
    }

    if ($return) {
        return vsprintf($format, $ary);
    } else {
        return vprintf($format, $ary);
    }
}

?>
mauf at franzoni dot info
16-Feb-2006 07:21
The format of floating values has been previously reporting as depending on platform (linux / windows) yet I see it changes within two linux systems depending on the version:
In V4.2.2 "%3.2" displays 3 integers and two decimals (i.e. the first digit represents just the number of integer digits), on V4.4.1 the same displays (and justifies the string to) a three character string (i.e. the first digit is the total lenght of the number, including the decimal dot).

Maybe someone may better specify which version this happens from.
darkfalconIV at hotmail dot com
18-Dec-2005 12:57
henke dot andersson

You can accomplish feeding it array if you use call_user_func_array. Not exactly a `clean' option, but it does work.
jonybd
14-Nov-2005 06:02
Time ? Format

<?php

$v_Dur
= "66";
$v_Dur = floor($v_Dur/60) . ":" number_format( fmod(($v_Dur/60)*60,60) )  ;
echo
"HH:MM========" . $v_Dur;

echo
"<br>";

$v_Dur = "66";
$v_Dur = floor($v_Dur/60) . ":" sprintf("%02s",number_format( fmod(($v_Dur/60)*60,60) )  );
echo
"HH:MM========" . $v_Dur;

?>
tim dot brouckaert dot NOSPAM at gmail dot com
12-Oct-2005 05:35
If you want to center align some text using the printf or sprintf functions, you can just use the following:

function center_text($word){
    $tot_width = 30;
    $symbol = "-";
    $middle = round($tot_width/2);
    $length_word = strlen($word);
    $middle_word = round($length_word / 2);
    $last_position = $middle + $middle_word;
    $number_of_spaces = $middle - $middle_word;

    $result = sprintf("%'{$symbol}{$last_position}s", $word);
        for ($i = 0; $i < $number_of_spaces; $i++){
            $result .= "$symbol";
        }
    return $result;
}

$string = "This is some text";
print center_text($string);

off course you can modify the function to use more arguments.
webmaster at cafe-clope dot net
14-Aug-2005 09:47
trying to fix the multibyte non-compliance of sprintf, I came to that :

<?php
function mb_sprintf($format) {
   
$argv = func_get_args() ;
   
array_shift($argv) ;
    return
mb_vsprintf($format, $argv) ;
}

function
mb_vsprintf($format, $argv) {
   
$newargv = array() ;
   
   
preg_match_all("`\%('.+|[0 ]|)([1-9][0-9]*|)s`U", $format, $results, PREG_SET_ORDER) ;
   
    foreach(
$results as $result) {
        list(
$string_format, $filler, $size) = $result ;
        if(
strlen($filler)>1)
           
$filler = substr($filler, 1) ;
        while(!
is_string($arg = array_shift($argv)))
           
$newargv[] = $arg ;
       
$pos = strpos($format, $string_format) ;
       
$format = substr($format, 0, $pos)
                  . (
$size ? str_repeat($filler, $size-strlen($arg)) : '')
                    .
str_replace('%', '%%', $arg)
                    .
substr($format, $pos+strlen($string_format))
                    ;
    }
       
    return
vsprintf($format, $newargv) ;
}

?>

handle with care :
1. that function was designed mostly for utf-8. i guess it won't work with any static mb encoding.
2. my configuration sets the mbstring.func_overload configuration directive to 7, so you may wish to replace substr, strlen, etc. with mb_* equivalents.
3. since preg_* doesn't complies with mb strings, I used a '.+' in the regexp to symbolize an escaped filler character. That means, %'xy5s pattern will match, unfortunately. It is recomended to remove the '+', unless you are intending to use an mb char as filler.
4. the filler fills at left, and only at left.
5. I couldn't succeed with a preg_replace thing : the problem was to use the differents lengths of the string arguements in the same replacement, string or callback. That's why the code is much longuer than I expected.
6. The pattern wil not match any %1\$s thing... just was too complicated for me.
7. Although it has been tested, and works fine within the limits above, this is much more a draft than a end-user function. I would enjoy any improvment.

The test code below shows possibilities, and explains the problem that occures with an mb string argument in sprintf.

<?php
header
("content-type:text/plain; charset=UTF-8") ;
$mb_string = "x
Новости
11 июля 2007
Сайт запущен
© 2007 info@grandviewstudio.com
Z058440144362 Z348613067571