string sprintf ( string format [, mixed args])
포맷 문자열 format에 따라 생성한 문자열을 반환합니다.
포맷 문자열은 0개 이상의 지시어를 조합합니다: 일반 문자는 (%을 제외하고) 결과에 그대로 복사하고, 변환 특정어는 각각의 인자로 교체한 결과를 가집니다. 이는 sprintf()와 printf()에 모두 적용됩니다.
각각의 변환 특정어는 퍼센트 기호(%)에 다음의 요소들이 붙어서 구성됩니다:
-
선택적인 패딩 지정어는 적합한 문자열의 크기를 얻기 위한 패딩에 사용하는 문자를 지정합니다. 이는 스페이스 문자나 0 (제로 문자)일 수 있습니다. 기본값은 스페이스로 채웁니다. 다른 패딩 문자는 작은 따옴표(')를 앞에 붙여서 지정할 수 있습니다. 아래의 예제를 참고하십시오.
-
선택적인 정렬 지정어는 결과를 왼쪽 정렬할지, 오른쪽 정렬할 지를 결정합니다. 기본값은 오른쪽 정렬입니다; 여기에 - 문자를 사용하면 왼쪽 정렬이 됩니다.
-
선택적인 수, 너비 지정어는 얼마나 많은 문자(최소한)가 결과에 들어갈지를 결정합니다.
-
선택적인 정밀도 지정어는 부동 소수점 실수에서 얼마나 많은 소수점 아래의 수를 표시할지를 결정합니다. 이 옵션은 float형 이외에는 영향을 주지 않습니다. (수를 포맷하는 다른 유용한 함수에는 number_format()이 존재합니다.)
-
형 지정어는 인자 데이터를 어떤 형으로 취급할지 결정합니다. 가능한 형은:
% - 퍼센트 문자. 인자는 필요하지 않습니다. b - 인자를 정수로 취급하고, 2진수로 표현합니다. c - 인자를 정수로 취급하고, ASCII 값에 해당하는 문자로 표현합니다. d - 인자를 정수로 취급하고, (부호 있는) 10진수로 표현합니다. u - 인자를 정수로 취급하고, 부호 없는 10진수로 표현합니다. f - 인자를 float로 취급하고, 실수로 표현합니다. o - 인자를 정수로 취급하고, 8진수로 표현합니다. s - 인자를 문자열로 취급하고 표현합니다. x - 인자를 정수로 취급하고 16진수(소문자 표시)로 표현합니다. X - 인자를 정수로 취급하고, 16진수(대문자 표시)로 표현합니다.
PHP 4.0.6부터 포맷 문자열은 인자 넘버링/교환을 지원합니다. 다음은 예제입니다:
참고: printf(), sscanf(), fscanf(), vsprintf(), number_format().
16-Jun-2004 03: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)
09-May-2004 03: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
?>
17-Apr-2004 08: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.
29-Mar-2004 11:16
A really working one:
<?php
function cutzero($value) {
return preg_replace("/(\.?)0+$/", "", $value);
}
?>
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") ?
10-Jul-2003 04:45
decision within sprintf:
$a = "today";
$b = sprintf('This is %s', $a=='today' ? 'today':'not today');
echo $b;
// result: This is today
16-May-2003 11:02
Your cutzero function could be faster ;-)
return (double)$value;
But if you must have a function:
return preg_replace('/0+$/', '', $value);
08-May-2003 03: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
?>
01-Mar-2003 08:59
Pay attention, that PHP's printf() and sprintf() do NOT support special flags, as the '+' one (makes a sign appear before the number, regardless of whether it's negative or positive).
It took me a while to figure that out: you have to write it yourself...
use something similar to the following
($value >= 0) ? printf('+%d', $value) : printf('%d', $value);
18-Feb-2003 07: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
03-Dec-2002 04: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 ;)
16-Sep-2002 07: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.
11-Sep-2002 12: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).
03-Jul-2002 03: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);
27-Jun-2002 03: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)
);
}
-----------------------------
01-Jun-2002 08: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);
}
20-Feb-2002 10: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
10-Feb-2002 09: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)));
09-Jan-2002 08:49
The 'e' format specifier is not documented. However, it seems to work, but without showing the exponential part of the number.
This is a function to get the scientific representation of a number:
function sci($x, $d=-1) {
$e=floor(log10($x));
$x*=pow(10,-$e);
$fmt=($d>=0)?".".$d:"";
$e=($e>=0)?"+".sprintf("%02d",$e):"-".sprintf("%02d",-$e);
return sprintf("%".$fmt."fe%s",$x,$e);
}
It takes the number as the first parameter and the precision as the second. The precision is optional. The default precision for the 'f' format specifier is used if no precision is specified.
05-Dec-2001 06: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".)
27-Nov-2001 11: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;
15-Apr-2001 08:20
$a = 5;
// $a is a int
echo $5;
// Outputs:"5";
// If you would like to print $a as a bin,(101) like: 00000101 (8 digits)
sprintf("%8b", $a) // Witch returns exatly 00000101 (8 digits)
// My function looked like:
//////////////////////////////////////////
// By DrRex - www.DrRex.dk - 15/04-2001 //
// string bin(int dec) //
//////////////////////////////////////////
function bin($dec){
$bin = sprintf("%8b", $dec);
return $bin;
}
//////////////////////////////////////////
// Very short exampels how to use bin()
echo "\n1. 128(10) == ".bin(128)."(2)";
$hits = 100;
echo "\n2. Loaded ".bin($hits)."(2) times! Bib!";
// Not very usefull, nobody understands the number, exept if small counters like this one. If it wasn't 8(2) but FFFFFF(16) digits. I would give up...
// This would output:
1. 128(10) == 10000000(2)
2. Loaded 01100100(2) times! Bib!
-------------------------------------------------
Greetings from Christiania, Copenhagen, Denmark!
All code by DrRex
www.DrRex.dk
13-Apr-2001 07:45
presumably, if you wanted to fill out a HTML line with space, you could use:
$fill = " "; // what to fill
$digits = sprintf ("%'{$fill}d", $digit);
(oh, thanks to whoever above who I just copy and pasted these lines from).
=ruptured=
26-Mar-2001 01: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.
24-Mar-2001 12: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)
15-Mar-2001 02:55
as far as centering a string within a field size goes:
sprintf("%-=75s", $str);
17-Nov-2000 08: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
18-Sep-2000 01:23
My attempt at a syntax summary in BNF:
%[ |0|'character][-][number][.number]type.
Type is one of % (none), b (binary*), c (char*), d (int), f (double), o (octal*), s (string), x (hex*) *Treated as integers.
14-Apr-1999 02:12
Hey folks, don't forget to prefix a precision specifier with a period '.'!
Thus, to print a floating point number,
say $x, with two digits after the decimal point you would write:
printf( "%.2f", $x );
[출처] [PHP] sprintf 형식화한 문자열을 반환합니다.|작성자 강국
'Language > php' 카테고리의 다른 글
Spreadsheet_Excel_Writer 설치하기 (0) | 2010.03.18 |
---|---|
php 파일 다운로드 .... (0) | 2010.01.28 |
PHP 세션에서 시작, 변수등록, 변수삭제, 부수기 ... (0) | 2009.08.11 |
php + 오라클 프로시저 연동 ... (0) | 2009.07.05 |
php 오라클 함수 ... (0) | 2009.07.05 |