downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

sscanf> <soundex
Last updated: Fri, 24 Jul 2009

view this page in

sprintf

(PHP 4, PHP 5)

sprintf형식화한 문자열을 반환

설명

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

포맷 문자열 format 에 따라 생성한 문자열을 반환합니다.

인수

format

포맷 문자열은 0개 이상의 지시어를 조합합니다: 일반 문자는 (%을 제외하고) 결과에 그대로 복사하고, 변환 특정어는 각각의 인수로 교체한 결과를 가집니다. 이는 sprintf()printf()에 모두 적용됩니다.

각각의 변환 특정어는 퍼센트 기호(%)에 다음의 요소들이 붙어서 구성됩니다:

  1. 선택적인 부호 지정어는 숫자에 부호(-나 +)를 강제합니다. 기본값은 숫자가 음수일때만 - 부호를 사용합니다. 이 지정어는 양수일때도 + 부호를 붙이고, PHP 4.3.0에서 추가되었습니다.
  2. 선택적인 패딩 지정어는 적합한 문자열의 크기를 얻기 위한 패딩에 사용하는 문자를 지정합니다. 이는 스페이스 문자나 0 (제로 문자)일 수 있습니다. 기본값은 스페이스로 채웁니다. 다른 패딩 문자는 작은 따옴표(')를 앞에 붙여서 지정할 수 있습니다. 아래의 예제를 참고하십시오.
  3. 선택적인 정렬 지정어는 결과를 왼쪽 정렬할지, 오른쪽 정렬할 지를 결정합니다. 기본값은 오른쪽 정렬입니다; 여기에 - 문자를 사용하면 왼쪽 정렬이 됩니다.
  4. 선택적인 수, 너비 지정어는 얼마나 많은 문자(최소한)가 결과에 들어갈지를 결정합니다.
  5. 선택적인 정밀도 지정어는 부동소수점 수에서 얼마나 많은 소수점 아래의 수를 표시할지를 결정합니다. 이 지정어를 문자열에 사용하면, 잘라내는 점으로 작동하여 문자열의 최대 문자수를 제한합니다.
  6. 형 지정어는 인수 데이터를 어떤 형으로 취급할지 결정합니다. 가능한 형은:

    • % - 퍼센트 문자. 인수는 필요하지 않습니다.
    • b - 인수를 정수로 취급하고, 2진수로 표현합니다.
    • c - 인수를 정수로 취급하고, 아스키 값에 해당하는 문자로 표현합니다.
    • d - 인수를 정수로 취급하고, (부호 있는) 10진수로 표현합니다.
    • e - 인수를 과학 형식으로 취급합니다. (예. 1.2e+2) 정밀도 지정어는 PHP 5.2.1부터 소수점 아래 자리수를 정합니다. 이전 버전에서는 유효숫자의 갯수(하나 적음)로 취급했었습니다.
    • u - 인수를 정수로 취급하고, 부호 없는 10진수로 표현합니다.
    • f - 인수를 소수로 취급하고, 부동소수점 수로 표현합니다. (로케일 관련)
    • F - 인수를 소수로 취급하고, 부동소수점 수로 표현합니다. (로케일 무관) PHP 4.3.10과 PHP 5.0.3부터 사용할 수 있습니다.
    • o - 인수를 정수로 취급하고, 8진수로 표현합니다.
    • s - 인수를 문자열로 취급하고 표현합니다.
    • x - 인수를 정수로 취급하고 16진수(소문자 표시)로 표현합니다.
    • X - 인수를 정수로 취급하고, 16진수(대문자 표시)로 표현합니다.

포맷 문자열은 인수 넘버링/교환을 지원합니다. 다음은 예제입니다:

Example #1 인수 교환

<?php
$format 
= ;There are %d monkeys in the %s';
printf($format, $num, $location);
?>

이는 "There are 5 monkeys in the tree"를 출력할 것입니다. 그러나, 국제화를 위해서 포맷 문자열을 별도의 파일로 작성하고, 이것을 다음처럼 재작성했다고 생각해봅시다:

Example #2 인수 교환

<?php
$format 
'The %s contains %d monkeys';
printf($format$num$location);
?>

문제가 생겼습니다. 포맷 문자열에서의 순서와 코드에서 인수의 순서가 일치하지 않습니다. 여기서 코드를 수정하지 않고, 단순히 포맷 문자열에 어떤 인수를 가져올지를 지정할 수 있습니다. 포맷 문자열을 다음과 같이 작성하면 됩니다:

Example #3 인수 교환

<?php
$format 
'The %2$s contains %1$d monkeys';
printf($format$num$location);
?>

코드에 많은 인수를 추가하지 않고도 반복해서 출력할 수 있다는 추가적인 장점이 존재합니다. 예를 들면:

Example #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);
?>

args

...

반환값

형식화 문자열 format 에 따라서 생성된 문자열을 반환합니다.

변경점

버전 설명
4.0.6 인수 넘버링/교환 추가.

예제

Example #5 printf(): 다양한 예제

<?php
$n 
=  43951789;
$u = -43951789;
$c 65// 아스키 65는 'A'

// 이중 %%에 주목, '%' 문자를 출력합니다.
printf("%%b = '%b'\n"$n); // 2진 표현
printf("%%c = '%c'\n"$c); // 아스키 문자 출력, chr() 함수와 동일
printf("%%d = '%d'\n"$n); // 표준 정수
printf("%%e = '%e'\n"$n); // 과학 표현
printf("%%u = '%u'\n"$n); // 양의 정수에 대한 부호 없는 정수 표현
printf("%%u = '%u'\n"$u); // 음의 정수에 대한 부호 없는 정수 표현
printf("%%f = '%f'\n"$n); // 부동소수점 표현
printf("%%o = '%o'\n"$n); // 8진 표현
printf("%%s = '%s'\n"$n); // 문자열 표현
printf("%%x = '%x'\n"$n); // 16진 표현 (소문자)
printf("%%X = '%X'\n"$n); // 16진 표현 (대문자)

printf("%%+d = '%+d'\n"$n); // 양의 정수에 대한 부호지정어
printf("%%+d = '%+d'\n"$u); // 음의 정수에 대한 부호지정어
?>

위 예제의 출력:

%b = '10100111101010011010101101'
%c = 'A'
%d = '43951789'
%e = '4.39518e+7'
%u = '43951789'
%u = '4251015507'
%f = '43951789.000000'
%o = '247523255'
%s = '43951789'
%x = '29ea6ad'
%X = '29EA6AD'
%+d = '+43951789'
%+d = '-43951789'

Example #6 printf(): 문자열 지정어

<?php
$s 
'monkey';
$t 'many monkeys';

printf("[%s]\n",      $s); // 표준 문자열 출력
printf("[%10s]\n"     $s); // 공백으로 오른쪽 정렬
printf("[%-10s]\n",   $s); // 공백으로 왼쪽 정렬
printf("[%010s]\n",   $s); // 0 채우기도 문자열에 작동
printf("[%'#10s]\n",  $s); // 사용자 채우기 문자 '#' 사용
printf("[%10.10s]\n"$t); // 왼쪽 정렬이지만 10문자로 자름
?>

위 예제의 출력:

[monkey]
[    monkey]
[monkey    ]
[0000monkey]
[####monkey]
[many monke]

Example #7 sprintf(): 0으로 채운 정수

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

Example #8 sprintf(): 통화 표현하기

<?php
$money1 
68.75;
$money2 54.35;
$money $money1 $money2;
// echo $money 는 "123.1"를 출력합니다;
$formatted sprintf("%01.2f"$money);
// echo $formatted 는 "123.10"를 출력합니다.
?>

Example #9 sprintf(): 과학 표현

<?php
$number 
362525200;

echo 
sprintf("%.3e"$number); // 3.625e+8 출력
?>

참고

  • printf() - 형식화한 문자열을 출력
  • sscanf() - 문자열을 형식에 따라 해석
  • fscanf() - Parses input from a file according to a format
  • vsprintf() - Return a formatted string
  • number_format() - Format a number with grouped thousands



sscanf> <soundex
Last updated: Fri, 24 Jul 2009
 
add a note add a note User Contributed Notes
sprintf
Astone
16-Sep-2009 03:41
When you're using Google translator, you have to 'escape' the 'conversion specifications' by putting <span class="notranslate"></span> around them.

Like this:

<?php

function getGoogleTranslation($sString, $bEscapeParams = true)
{
   
// "escape" sprintf paramerters
   
if ($bEscapeParams)
    {
       
$sPatern = '/(?:%%|%(?:[0-9]+\$)?[+-]?(?:[ 0]|\'.)?-?[0-9]*(?:\.[0-9]+)?[bcdeufFosxX])/';       
       
$sEscapeString = '<span class="notranslate">$0</span>';
       
$sString = preg_replace($sPatern, $sEscapeString, $sString);
    }

   
// Compose data array (English to Dutch)
   
$aData = array(
       
'v'            => '1.0',
       
'q'            => $sString,
       
'langpair'    => 'en|nl',
    );

   
// Initialize connection
   
$rService = curl_init();
   
   
// Connection settings
   
curl_setopt($rService, CURLOPT_URL, 'http://ajax.googleapis.com/ajax/services/language/translate');
   
curl_setopt($rService, CURLOPT_RETURNTRANSFER, true);
   
curl_setopt($rService, CURLOPT_POSTFIELDS, $aData);
   
   
// Execute request
   
$sResponse = curl_exec($rService);

   
// Close connection
   
curl_close($rService);
   
   
// Extract text from JSON response
   
$oResponse = json_decode($sResponse);
    if (isset(
$oResponse->responseData->translatedText))
    {
       
$sTranslation = $oResponse->responseData->translatedText;
    }
    else
    {
       
// If some error occured, use the original string
       
$sTranslation = $sString;
    }
   
   
// Replace "notranslate" tags
   
if ($bEscapeParams)
    {
       
$sEscapePatern = '/<span class="notranslate">([^<]*)<\/span>/';
       
$sTranslation = preg_replace($sEscapePatern, '$1', $sTranslation);
    }
   
   
// Return result
   
return $sTranslation;
}

?>

Thanks to MelTraX for defining the RegExp!
Jay Gilford
26-Aug-2009 09:13
I created this function a while back to save on having to combine mysql_real_escape_string onto all the params passed into a sprintf. it works literally the same as the sprintf other than that it doesn't require you to escape your inputs. Hope its of some use to people

<?php
function mressf()
{
   
$args = func_get_args();
    if (
count($args) < 2)
        return
false;
   
$query = array_shift($args);
   
$args = array_map('mysql_real_escape_string', $args);
   
array_unshift($args, $query);
   
$query = call_user_func_array('sprintf', $args);
    return
$query;
}
?>

Regards
Jay
Jaygilford.com
jfgrissom at gmail dot com
12-Jul-2009 01:51
I had a nightmare trying to find the two's complement of a 32 bit number.

I got this from http://www.webmasterworld.com/forum88/13334.htm (credit where credit is due... =P  )

Quote: ...find out the 2's complement of any number, which is -(pow(2, n) - N) where n is the number of bits and N is the number for which to find out its 2's complement.

This worked magic for me... previously I was trying to use

sprintf ("%b",$32BitDecimal);
But it always returned 10000000000000000000000 when the $32BitDecimal value got above 2,000,000,000.

This -(pow(2, n) - N)
Worked remarkably well and was very accurate.

Hope this helps someone fighting with two's complement in PHP.
John Walker
10-Jul-2009 09:56
To add to other notes below about floating point problems, I noted that %f and %F will apparently output a maximum precision of 6 as a default so you have to specify 1.15f (eg) if you need more.

In my case, the input (from MySQL) was a string with 15 digits of precision that was displayed with 6. Likely what happens is that the rounding occurs in the conversion to a float before it is displayed. Displaying it as 1.15f (or in my case, %s) shows the correct number.
viktor at textalk dot com
19-Feb-2009 01:16
A more complete and working version of mb_sprintf and mb_vsprintf. It should work with any "ASCII preserving" encoding such as UTF-8 and all the ISO-8859 charsets. It handles sign, padding, alignment, width and precision. Argument swapping is not handled.

<?php
if (!function_exists('mb_sprintf')) {
  function
mb_sprintf($format) {
     
$argv = func_get_args() ;
     
array_shift($argv) ;
      return
mb_vsprintf($format, $argv) ;
  }
}
if (!
function_exists('mb_vsprintf')) {
 
/**
   * Works with all encodings in format and arguments.
   * Supported: Sign, padding, alignment, width and precision.
   * Not supported: Argument swapping.
   */
 
function mb_vsprintf($format, $argv, $encoding=null) {
      if (
is_null($encoding))
         
$encoding = mb_internal_encoding();

     
// Use UTF-8 in the format so we can use the u flag in preg_split
     
$format = mb_convert_encoding($format, 'UTF-8', $encoding);

     
$newformat = ""; // build a new format in UTF-8
     
$newargv = array(); // unhandled args in unchanged encoding

     
while ($format !== "") {
     
       
// Split the format in two parts: $pre and $post by the first %-directive
        // We get also the matched groups
       
list ($pre, $sign, $filler, $align, $size, $precision, $type, $post) =
           
preg_split("!\%(\+?)('.|[0 ]|)(-?)([1-9][0-9]*|)(\.[1-9][0-9]*|)([%a-zA-Z])!u",
                      
$format, 2, PREG_SPLIT_DELIM_CAPTURE) ;

       
$newformat .= mb_convert_encoding($pre, $encoding, 'UTF-8');
       
        if (
$type == '') {
         
// didn't match. do nothing. this is the last iteration.
       
}
        elseif (
$type == '%') {
         
// an escaped %
         
$newformat .= '%%';
        }
        elseif (
$type == 's') {
         
$arg = array_shift($argv);
         
$arg = mb_convert_encoding($arg, 'UTF-8', $encoding);
         
$padding_pre = '';
         
$padding_post = '';
         
         
// truncate $arg
         
if ($precision !== '') {
           
$precision = intval(substr($precision,1));
            if (
$precision > 0 && mb_strlen($arg,$encoding) > $precision)
             
$arg = mb_substr($precision,0,$precision,$encoding);
          }
         
         
// define padding
         
if ($size > 0) {
           
$arglen = mb_strlen($arg, $encoding);
            if (
$arglen < $size) {
              if(
$filler==='')
                 
$filler = ' ';
              if (
$align == '-')
                 
$padding_post = str_repeat($filler, $size - $arglen);
              else
                 
$padding_pre = str_repeat($filler, $size - $arglen);
            }
          }
         
         
// escape % and pass it forward
         
$newformat .= $padding_pre . str_replace('%', '%%', $arg) . $padding_post;
        }
        else {
         
// another type, pass forward
         
$newformat .= "%$sign$filler$align$size$precision$type";
         
$newargv[] = array_shift($argv);
        }
       
$format = strval($post);
      }
     
// Convert new format back from UTF-8 to the original encoding
     
$newformat = mb_convert_encoding($newformat, $encoding, 'UTF-8');
      return
vsprintf($newformat, $newargv);
  }
}
?>
splogamurugan at gmail dot com
06-Feb-2009 10:59
$format = 'There are %1$d monkeys in the %s and %s ';
printf($format, 100, 'Chennai', 'Bangalore');

Expecting to output
"There are 100 monkeys in the Chennai and bangalore"

But, this will output
"There are 100 monkeys in the 100 and Chennai"

Because, the second and Third specifiers takes 1rst and 2nd arguments. Because it is not assigned with any arguments.
remy dot damour at -please-no-spam-laposte dot net
16-Jan-2009 04:15
With printf() and sprintf() functions, escape character is not backslash '\' but rather '%'.

Ie. to print '%' character you need to escape it with itself:
<?php
printf
('%%%s%%', 'koko'); #output: '%koko%'
?>
MelTraX
06-Nov-2008 06:40
<?php
 
// parses a string meant for printf and returns an array of found parameters (or NULL if it contains syntax errors)
 
function parsePrintfParameters($string) {
   
$valid = '/^(?:%%|%(?:[0-9]+\$)?[+-]?(?:[ 0]|\'.)?-?[0-9]*(?:\.[0-9]+)?[bcdeufFosxX])/';
   
$originalString = $string;

   
$result = array();
    while(
strlen($string)) {
      if(!
$string = preg_replace('/^[^%]*/', '', $string))
        break;

      if(
preg_match($valid, $string, $matches)) {
       
$result[] = $matches[0];
       
$string = substr($string, strlen($matches[0]));
      } else {
       
error(sprintf('"%s" has an error near "%s".', $originalString, $string));
        return
NULL;
      }
    }
    return
$result;
  }
?>
savannah at seznam dot cz
12-Oct-2008 08:29
If you have problems using utf-8 with string paddings, you can use this function:

<?php
/**
 * Formats string using sprintf, but correctly handles %s  with space paddings
 *
 * uses conversion to iso-8859-2 and back
 *
 * it is, however, much slower, so use only when needed!
 *
 * @param string $format
 */
function utf_8_sprintf ($format) {
 
$args = func_get_args();

  for (
$i = 1; $i < count($args); $i++) {
   
$args [$i] = iconv('UTF-8', 'ISO-8859-2', $args [$i]);
  }
 
  return
iconv('ISO-8859-2', 'UTF-8', call_user_func_array('sprintf', $args));
}

// test

echo sprintf ("[%-20s]\n", 'escrzyaie'); //  how it should look without special chars
echo sprintf ("[%-20s]\n", 'ěščřžýáíé'); // not correctly handled by php
echo utf_8_sprintf ("[%-20s]\n", 'ěščřžýáíé'); // using above function

/*
produces:
[escrzyaie           ]
[ěščřžýáíé  ]
[ěščřžýáíé           ]
*/

?>
the trick is to convert arguments to iso8859-2 and result back to utf-8.
php at mikeboers dot com
02-Oct-2008 05:42
And continuing on the same theme of a key-based sprintf...

I'm roughly (I can see a couple cases where it comes out wierd) copying the syntax of Python's string formatting with a dictionary. The improvement over the several past attempts is that this one still respects all of the formating options, as you can see in my example.

And the error handling is really crappy (just an echo). I just threw this together so do with it what you will. =]

<?php

function sprintf_array($string, $array)
{
   
$keys    = array_keys($array);
   
$keysmap = array_flip($keys);
   
$values  = array_values($array);
   
    while (
preg_match('/%\(([a-zA-Z0-9_ -]+)\)/', $string, $m))
    {   
        if (!isset(
$keysmap[$m[1]]))
        {
            echo
"No key $m[1]\n";
            return
false;
        }
       
       
$string = str_replace($m[0], '%' . ($keysmap[$m[1]] + 1) . '$', $string);
    }
   
   
array_unshift($values, $string);
   
var_dump($values);
    return
call_user_func_array('sprintf', $values);
}

echo
sprintf_array('4 digit padded number: %(num)04d ', array('num' => 42));

?>

Cheers!
ant at loadtrax dot com
18-Jun-2008 06:19
Rounding seems a little inconsistent, so beware:

$ php -a

php> print round(1.0*20*1.175/100,2);
0.24
php > print sprintf("%.2f",1.0*20*1.175/100);
0.23
php > print sprintf("%.0f",1.0*20*1.175);
24

I get round this by doing the round first, then doing the sprintf.
jaimthorn at yahoo dot com
11-Jun-2008 11:01
I needed a piece of code similar to the one Matt posted below, on the 10th of March, 2008.  However, I wasn't completely satisfied with Matt's code (sorry, Matt!  No offense intended!), because

1) I don't like to initialize variables when it's not really needed, and
2) it contains two bugs.

What are the bugs?

First, Matt's code tests for count($vars) > 0, but if $var == "Hello world!", then count($var) == 1, but the foreach() will crash because $var has to be an array.  So instead, my code tests for is_array($var).

Second, if a key in $vars is a prefix of any of the later keys in the array (like 'object' is the beginning of 'objective') then the str_replace messes things up.  This is no big deal if your keys are hard-coded and you can make sure the keys don't interfere, but in my code the keys are variable.  So I decided to first sort the array on a decreasing length of the key.

<?php

function cmp($a, $b)
{
    return
strlen($b) - strlen($a);
}

function
sprintf2($str, $vars, $char = '%')
{
    if(
is_array($vars))
    {
       
uksort($vars, "cmp");

        foreach(
$vars as $k => $v)
        {
           
$str = str_replace($char . $k, $v, $str);
        }
    }

    return
$str;
}

echo
sprintf2( 'Hello %your_name, my name is %my_name! I am %my_age, how old are you? I like %object and I want to %objective_in_life!'
            
, array( 'your_name'         => 'Matt'
                   
, 'my_name'           => 'Jim'
                   
, 'my_age'            => 'old'
                   
, 'object'            => 'women'
                   
, 'objective_in_life' => 'write code'
                   
)
             );

?>

If possible, and if you're willing, you can also embed the key fields in the text between percent-signs, rather than prefixing the keys with one.  Sorting is no longer necessary, and the execution time is less than half of the code above:

<?php

function sprintf3($str, $vars, $char = '%')
{
   
$tmp = array();
    foreach(
$vars as $k => $v)
    {
       
$tmp[$char . $k . $char] = $v;
    }
    return
str_replace(array_keys($tmp), array_values($tmp), $str);
}

echo
sprintf3( 'Hello %your_name%, my name is %my_name%! I am %my_age%, how old are you? I like %object% and I want to %objective_in_life%!'
            
, array( 'your_name'         => 'Matt'
                   
, 'my_name'           => 'Jim'
                   
, 'my_age'            => 'old'
                   
, 'object'            => 'women'
                   
, 'objective_in_life' => 'write code'
                   
)
             );
?>

If you're willing to embed the keys in the text, you may also be willing to embed the keys themselves in percent signs, thus shaving off another 30% of the execution time:

<?php

function sprintf4($str, $vars)
{
    return
str_replace(array_keys($vars), array_values($vars), $str);
}

echo
sprintf4( 'Hello %your_name%, my name is %my_name%! I am %my_age%, how old are you? I like %object% and I want to %objective_in_life%!'
            
, array( '%your_name%'         => 'Matt'
                   
, '%my_name%'           => 'Jim'
                   
, '%my_age%'            => 'old'
                   
, '%object%'            => 'women'
                   
, '%objective_in_life%' => 'write code'
                   
)
             );
?>

Of course, by now the sprintf function is no longer something you'd want to write to mum and dad about...
ranema at ubuntu dot polarhome dot com
31-Mar-2008 12:40
It's very comfortible for long Sql queries:

<?php
$_gQuery
= "UPDATE `x` SET `a` = %i AND `b` = '%s' WHERE `my` = '%s';"; // ........

mysql_query( sprintf( $_gQuery, 10, 'a', 'rrrr' ) );
?>

But if you have a short query, then it would be much faster to append your data by using `.`.

<?php
$_gQuery
= 'SELECT COUNT(*) FROM `' . $_gName . '`;';
?>
matt
11-Mar-2008 02:13
Was looking for a assoc way of using sprintf but couldnt find one, probably wasnt looking hard enough so came up with this. Very very simple indeed...

<?php

function sprintf2($str='', $vars=array(), $char='%')
{
    if (!
$str) return '';
    if (
count($vars) > 0)
    {
        foreach (
$vars as $k => $v)
        {
           
$str = str_replace($char . $k, $v, $str);
        }
    }

    return
$str;
}

echo
sprintf2('Hello %your_name my name is %my_name! I am %my_age, how old are you? I like %object!', array(
   
'your_name' => 'Ben',
   
'my_name' => 'Matt',
   
'my_age' => '21',
   
'object' => 'food'
));

// Hello Ben my name is Matt! I am 21, how old are you? I like food!

?>

Looks nice anyway :)
andyhaslam at hotmail dot com
06-Feb-2008 02:46
An interesting bug, if you do the following:

$val = 2345.35;
$val = sprintf("%01.2f", $val);
echo $val;

Output is "2.00", instead of "2345.35". The solution is to use an intermediate variable:

$val = 2345.35;
$val2 = sprintf("%01.2f", $val);
$val = $val2;
echo $val;
scott dot gardner at mac dot com
11-Jan-2008 06:22
In the last example of Example#6, there is an error regarding the output.

printf("[%10.10s]\n", $t); // left-justification but with a cutoff of 10 characters

This outputs right-justified.

In order to output left-justified:

printf("[%-10.10s]\n", $t);
me at umarfarooq dot net
07-Sep-2007 03: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 04: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 04: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;
}
?>
30-Jan-2007 03: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
10-Nov-2006 04: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
17-Oct-2006 08: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 06: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
13-Aug-2006 03: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
11-Aug-2006 06: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
07-Aug-2006 02: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 05: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
17-Feb-2006 12: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
19-Dec-2005 05: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.
tim dot brouckaert dot NOSPAM at gmail dot com
12-Oct-2005 09: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
15-Aug-2005 01: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 = "xxx" ;
echo
sprintf("%010s", $mb_string), " [octet-size: ", str_sizeof($mb_string) , " ; count: ", strlen(sprintf("%010s", $mb_string)), " characters]\n" ;
echo
mb_sprintf("%010s", $mb_string), " [octet-size: ", str_sizeof($mb_string) , " ; count: ", strlen(mb_sprintf("%010s", $mb_string)), " characters]\n" ;
echo
"\n" ;
echo
mb_sprintf("%''10s\n%'010s\n%'10s\n%10d\n%'x10s\n%010s\n% 10s\n%010s\n%'1s\n", "zero", "one", "two", 3, "four", "ve", "%s%i%x", "ve", "eight") ;
?>
david at rayninfo dot co dot uk
17-Jun-2005 03:33
Using sprintf to force leading leading zeros

foreach (range(1, 10) as $v) {echo "<br>tag_".sprintf("%02d",$v);}

displays
tag_01
tag_02
tag_03
.. etc
ian dot w dot davis at gmail dot com
30-May-2005 11:03
Just to elaborate on downright's point about different meanings for %f, it appears the behavior changed significantly as of 4.3.7, rather than just being different on different platforms. Previously, the width specifier gave the number of characters allowed BEFORE the decimal. Now, the width specifier gives the TOTAL number of characters. (This is in line with the semantics of printf() in other languages.) See bugs #28633 and #29286 for more details.
Pacogliss
02-May-2005 04:08
Just a reminder for beginners : example 6 'printf("[%10s]\n",    $s);' only works (that is, shows out the spaces) if you put the html '<pre></pre>' tags ( head-scraping time saver ;-).
christian at wenz dot org
18-Apr-2005 04:20
@ henke dot andersson at comhem dot se: Use vprintf()/vsprintf() for that.
henke dot andersson at comhem dot se
16-Apr-2005 12:07
Mind that it doesn't allow you to use a array as multiple arguments like this:
<?php
printf
('%s %s',array('a','b')) ?>
downright at comcast dot net
01-Feb-2005 07:03
Just thought I'd give a heads up for anyone doing cross platform applications.

sprintf spacing is different numerically with Windows and Linux.

Linux aligned correctly:
$ol = sprintf ("%-6s|%11.2f|%11.2f|%11.2f|%11.2f|%11.2f|%11.2f|%11.2f|%11.2f\n",

Windows aligned correctly:
$ol = sprintf ("%-6s|%14.2f|%14.2f|%14.2f|%14.2f|%14.2f|%14.2f|%14.2f|%14.2f\n",

As you can see the strings are fine for spacing, however, the numbers need a difference of 3 in order to have the same amount of spaces.

I noticed this after using sprintf to format a header for a web app I was working on.  On windows it fit, however, when it came to linux it was MUCH larger than the header.
jrpozo at conclase dot net
22-Jan-2005 12:13
Be careful if you use the %f modifier to round decimal numbers as it (starting from 4.3.10) will no longer produce a float number if you set certain locales, so you can't accumulate the result. For example:

setlocale(LC_ALL, 'es_ES');
echo(sprintf("%.2f", 13.332) + sprintf("%.2f", 14.446))

gives 27 instead of 27.78, so use %F instead.
timo at frenay dot net
11-Jan-2005 03:58
Note that the documentation is unclear about the details of the sign specifier. First of all, the character for this is "+".

Also note that the following does NOT print "+00.00" as you might expect:

<?php
    printf
('%+02.2f', 0);
?>

The sign is included in the width. This can't be solved by increasing the width:

<?php
    printf
('%+03.2f', 0);
?>

This will put the padding 0 before the sign.
Here is a possible solution:

<?php
    $value
= 0;
   
printf('%s%02.2f', ($value < 0) ? '-' : '+', abs($value));
?>
Gkeeper80
12-Aug-2004 07:58
When using sprintf with padding, it's important to note that specifying the length of your padding does not restrict the length of your output.

For example:
$var = 'test';
$output sprintf("%03s", $var);

print $output;

Produces:
test

NOT:
est

This may seem intuitive for working with numbers, but not neccesarily when working with strings.
rex
16-Jun-2004 06:47
Note, if you are just looking for something to pad out a string consider str_pad.

From testing, it seems faster and was more intuitive to use (for example, making it pad the begining or end of a string... with sprintf you would have to use negative indexes)
php at sharpdreams dot com
09-May-2004 06:13
Note that when using the argument swapping, you MUST number every argument, otherwise sprintf gets confused. This only happens if you use number arguments first, then switch to a non-numbered, and then back to a numbered one.

<?php
$sql
= sprintf( "select * from %1\$s left join %2\$s on( %1\$s.id = %2\$s.midpoint ) where %1\$s.name like '%%%s%%' and %2\$s.tagname is not null", "table1", "table2", "bob" );
// Wont work:
// Sprintf will complain about not enough arguments.
$sql = sprintf( "select * from %1\$s left join %2\$s on( %1\$s.id = %2\$s.midpoint ) where %1\$s.name like '%%%3\$s%%' and %2\$s.tagname is not null", "table1", "table2", "bob" );
// Will work: note the %3\$s
?>
tobias at silverxnet dot de
17-Apr-2004 11:09
Regarding the previous posting:
I just wanted to give an explanation. This should be because the float to string / integer to string conversion (you are using a string, multiplying it with a float value what php automatically causes to convert the string to a float value). This is a general "problem" (or not), but not that hard to explain.
Where an integer or float starts with 0, in a string it does obviously with 1. So if you are using a string your value will increase by one (You started with a string, so it does not increase but contain the real result. If you start using a float value by not using '' around the value, you have to output the float value as well. This is just the PHP conversion.)

Try putting
$x = strval( $x );
after
$x = $x * 100;
and using your example again. You will see that the output will change to 13664 = 13664 because of the general string conversion. It seems that PHP is converting a float to a string by inceasing by one. By doing the same with intval instead of strval the output changes to 13663 = 13663.

! sprintf seems to behave wrong when using the conversation to an integer value and NOT doing the conversation at all. So use intval to convert to an integer value or strval to convert to a string value BEFORE using sprintf. This should be solving the problems.
kekec at kukac dot hu
30-Mar-2004 02:16
A really working one:
<?php
function cutzero($value) {
   return
preg_replace("/(\.?)0+$/", "", $value);
}
?>
06-Mar-2004 03:54
both of your cut-zero functions are just way too complicated. if it's a string where only the zeros at the end should be truncated, why not use a syntax as simple as rtrim("4.7000","0") ?
Rene dot Leonhardt at agritec24 dot com
17-May-2003 02:02
Your cutzero function could be faster ;-)
   return (double)$value;

But if you must have a function:
   return preg_replace('/0+$/', '', $value);
kouber at php dot net
08-May-2003 06:55
If you want to cut all the zeros off the end of a float, but not losing any sensitive information, use this:

<?
function cutzero($value) {
    return
preg_replace("/(\.\d+?)0+$/", "$1", $value)*1;
}
?>

Some examples:

<?
cutzero
("4.7600");     // returns 4.76
cutzero("4.7604")      // returns 4.7604
cutzero("4.7000");     // returns 4.7
cutzero("4.0000");     // returns 4
?>
info at nospam dot webtip dot dk
18-Feb-2003 10:06
If you want to format a phonenumber with spaces, use chunk_split() which splits a string into smaller chunks. It's much simpler than using sprintf.

$phone = "12345678";

chunk_split ($phone, 2);

will return 12 34 56 78
moritz dot geselle at invision-team dot de
03-Dec-2002 07:52
a little note to the argument swapping examples which took me a while to get:
if you use single quotes for the format string (like you should do, since there aren't any variable conversions to do as long as you don't need any special chars), the given examples won't work because of the backslash before the $ (needs to be escaped in double quoted strings - but not in single quoted!)

so this:

$format = "The %2\$s contains %1\$d monkeys";
printf($format,$num,$location);

with a single quoted format string would look like this:

$format = 'The %2$s contains %1$d monkeys';
printf($format,$num,$location);

(no escapes)

I hope that helps to avoid confusion ;)
no dot email dot address at example dot com
16-Sep-2002 10:29
Using argument swapping in sprintf() with gettext: Let's say you've written the following script:

<?php
$var
= sprintf(gettext("The %2\$s contains %1\$d monkeys"), 2, "cage");
?>

Now you run xgettext in order to generate a .po file. The .po file will then look like this:

#: file.php:9
#, ycp-format
msgid "The %2\\$s contains %1\\$d monkeys"
msgstr ""

Notice how an extra backslash has been added by xgettext.

Once you've translated the string, you must remove all backslashes from the ID string as well as the translation, so the po file will look like this:

#: file.php:9
#, ycp-format
msgid "The %2$s contains %1$d monkeys"
msgstr "Der er %1$d aber i %2$s"

Now run msgfmt to generate the .mo file, restart Apache to remove the gettext cache if necessary, and you're off.
abiltcliffe at bigfoot.com
11-Sep-2002 03:01
To jrust at rustyparts.com, note that if you're using a double-quoted string and *don't* escape the dollar sign with a backslash, $s and $d will be interpreted as variable references. The backslash isn't part of the format specifier itself but you do need to include it when you write the format string (unless you use single quotes).
Andrew dot Wright at spamsux dot atnf dot csiro dot au
03-Jul-2002 06:22
An error in my last example:
$b = sprintf("%30.s", $a);
will only add enough spaces before $a to pad the spaces + strlen($a) to 30 places.

My method of centering fixed text in a 72 character width space is:

$a = "Some string here";
$lwidth = 36; // 72/2
$b = sprintf("%".($lwidth + round(strlen($a)/2)).".s", $a);
eden_zero_x at hotmail dot com
27-Jun-2002 06:05
Well I came up with this one, extremely simple. instead of writing <span class="class">hello</a>
you can write: print class('class','hello'); using sprintf
-----------------------------
function class_ ($class, $text=false)
 {
    return sprintf ("<span class=\"%s\">%s</span>",
        $class,
        ($text ? $text : $class)
    );
 }
-----------------------------
shgyn at binabakti dot or dot id
01-Jun-2002 11:57
Previously submitted sci() function to get scientific representation of a number is not working with 0 and negative numbers. So, here is the modified version:

function sci($x, $d=-1) {
    $min=($x<0)?"-":"";
    $x=abs($x); 
    $e=floor(($x!=0)?log10($x):0);
    $x*=pow(10,-$e);
    $fmt=($d>=0)?".".$d:"";
    $e=($e>=0)?"+".sprintf("%02d",$e):"-".sprintf("%02d",-$e);
    return sprintf("$min%".$fmt."fe%s",$x,$e);
}
fuchschr at surfeu dot at
21-Feb-2002 01:54
To have a string with leading zeros use this:
$string_i = sprintf("%04s",$value)

Gives you an output with leading zeros and 4 digits.
i.e.
0001
0002
...
0010
an so on
cv at corbach dot de
11-Feb-2002 12:36
To make radu.rendec@ines.ro's excellent function work on signed numbers you must change the first line to:

$e = floor(log10(abs($x)));
anqmb(at)yahoo.co.jp
05-Dec-2001 09:51
Watch out the mysterious rounding rule.
<?php
$a
= 4.5;
$b = sprintf("%d",$a);
$c = 4.5;
$d = sprintf("%.0f",$c);
$e = 0.45;
$f = sprintf("%.1f",$e);
print (
"$b,$d,$f\n");
?>

The code above prints "4,5,0.5".
(Perl version prints "4,4,0.5".)
keeper at odi dot com dot br
27-Nov-2001 02:26
Took me a while to find this out.
hope will save someones time.
IT ADD A CARACRER TO THE END OF A STRING

$x = sprintf("%'x-10s", "a");
echo $x;
tjchamberlain.hotmail@com
26-Mar-2001 04:16
It is worth noting that "%5.2f" will result in a string 8 characters long (5 then the '.' then 2), not 5 characters as you might expect.
prolixmp3 at navigators dot lv
24-Mar-2001 03:55
If you are going to create a counter which uses _symbols_ before actual digits (see, f.e., SpyLog.com counters - they are filling space with "." before, so the count like 12345 looks like "........12345"), you can use the following:

$txt = "Abracadabra"; // actual string
$fit = 16; // how many digits to use
$fill = "."; // what to fill
$digits = sprintf ("%'{$fill}{$fit}s", $txt);

Paul (a.k.a. Mr.Prolix)
voudras at nospam dot swiftslayer dot org
17-Nov-2000 11:58
Little note about sprintf and its ilk.
if you attempt something like
$string = "dingy%sflem%dwombat";
$nbr = 5;
$name = "voudras";

$msg = sprintf("%d $string %s", $nbr, $name);

sprintf will complain about a lack in the number of arguments, this would be because of the %'s in the actual string. This can be a great benifit, but is also rather confusing if you dont realize this feature, and are passing questionable variables to sprintf (for, say perhaps logging). One way around this is using
ereg_replace("%","%%", $string); before
sending it off to sprintf. This is actually how i came across this as a problem - i had realized some time ago that i would have to test my $string for
%'s, but when running the %->%% replacement on a very large serialized object, my application timed out.
    My solution was to use
sprintf("%d %s %s", $nbr, $string, $name);
but, there was a reason i originally had done this the other way - i suppose i'll find out soon enough

sscanf> <soundex
Last updated: Fri, 24 Jul 2009
 
 
show source | credits | stats | sitemap | contact | advertising | mirror sites