PHP printf() 함수
예시
형식이 지정된 문자열을 출력합니다.
<?php
$number = 9;
$str = "Beijing";
printf("There are %u million bicycles in %s.",$number,$str);
?>
정의 및 사용
printf() 함수는 형식이 지정된 문자열을 출력합니다.
arg1, arg2, ++ 매개변수는 기본 문자열의 백분율(%) 기호에 삽입됩니다. 이 기능은 "단계적"으로 작동합니다. 첫 번째 % 기호에 arg1이 삽입되고 두 번째 % 기호에 arg2가 삽입되는 식입니다.
참고: 인수보다 % 기호가 더 많은 경우 자리 표시자를 사용해야 합니다. 자리 표시자는 % 기호 뒤에 삽입되며 인수 번호와 "\$"로 구성됩니다. 예 2를 참조하십시오.
팁: 관련 함수: sprintf() , vprintf() , vsprintf() , fprintf() 및 vfprintf()
통사론
printf(format,arg1,arg2,arg++)
매개변수 값
Parameter | Description |
---|---|
format | Required. Specifies the string and how to format the variables in it. Possible format values:
Additional format values. These are placed between the % and the letter (example %.2f):
Note: If multiple additional format values are used, they must be in the same order as above. |
arg1 | Required. The argument to be inserted at the first %-sign in the format string |
arg2 | Optional. The argument to be inserted at the second %-sign in the format string |
arg++ | Optional. The argument to be inserted at the third, fourth, etc. %-sign in the format string |
기술적 세부 사항
반환 값: | 출력된 문자열의 길이를 반환 |
---|---|
PHP 버전: | 4+ |
더 많은 예
예시
형식 값 %f 사용:
<?php
$number = 123;
printf("%f",$number);
?>
예시
자리 표시자의 사용:
<?php
$number = 123;
printf("With 2 decimals: %1\$.2f
<br>With no decimals: %1\$u",$number);
?>
예시
가능한 모든 형식 값의 데모:
<?php
$num1 = 123456789;
$num2 = -123456789;
$char = 50; // The ASCII Character 50 is 2
// Note: The format value "%%" returns a percent sign
printf("%%b = %b <br>",$num1); // Binary number
printf("%%c = %c <br>",$char); // The ASCII Character
printf("%%d = %d <br>",$num1); // Signed decimal number
printf("%%d = %d <br>",$num2); // Signed decimal number
printf("%%e = %e <br>",$num1); // Scientific notation (lowercase)
printf("%%E = %E <br>",$num1); // Scientific notation (uppercase)
printf("%%u = %u <br>",$num1); // Unsigned decimal number (positive)
printf("%%u = %u <br>",$num2); // Unsigned decimal number (negative)
printf("%%f = %f <br>",$num1); // Floating-point number (local settings aware)
printf("%%F = %F <br>",$num1); // Floating-point number (not local settings aware)
printf("%%g = %g <br>",$num1); // Shorter of %e and %f
printf("%%G = %G <br>",$num1); // Shorter of %E and %f
printf("%%o = %o <br>",$num1); // Octal number
printf("%%s = %s <br>",$num1); // String
printf("%%x = %x <br>",$num1); // Hexadecimal number (lowercase)
printf("%%X = %X <br>",$num1); // Hexadecimal number (uppercase)
printf("%%+d = %+d <br>",$num1); // Sign specifier (positive)
printf("%%+d = %+d <br>",$num2); // Sign specifier (negative)
?>
예시
문자열 지정자 데모:
<?php
$str1 = "Hello";
$str2 = "Hello world!";
printf("[%s]<br>",$str1);
printf("[%8s]<br>",$str1);
printf("[%-8s]<br>",$str1);
printf("[%08s]<br>",$str1);
printf("[%'*8s]<br>",$str1);
printf("[%8.8s]<br>",$str2);
?>
❮ PHP 문자열 참조