PHP/Utility Function/printf

Материал из Web эксперт
Перейти к: навигация, поиск

Adding the
 and 
tags so the spaces display

 
<?php
printf("<pre>Space padding can be tricky in HTML % 5d.</pre
>", 42);
?>



Demonstrating Some Type Specifiers

 
<html>
<head>
<title>Demonstrating Some Type Specifiers</title>
</head>
<body>
<div>
<?php
    $number = 543;
    printf("Decimal: %d<br/>", $number );
    printf("Binary: %b<br/>", $number );
    printf("Double: %f<br/>", $number );
    printf("Octal: %o<br/>", $number );
    printf("String: %s<br/>", $number);
    printf("Hex (lower): %x<br/>", $number );
    printf("Hex (upper): %X<br/>", $number );
?>
</div>
</body>
</html>



Displaying a real number in money format

 
<?php
printf("Please pay $%.2f. ", 42.4242);
?>



Displaying long text with an ellipsis

 
<?
printf(substr_replace("this is a test"," ...",5));
?>



Displaying signs with printf()

 
<?
$min = -40;
$max = 40;
printf("The computer can operate between %+d and %+d degrees Celsius.", $min, $max);
?>



Displaying the same number in different formats

 
<?php
$value=42;
printf("%d<br />",$value);
printf("%b<br />",$value);
printf("%c<br />",$value);
printf("%f<br />",$value);
printf("%o<br />",$value);
printf("%s<br />",$value);
printf("%x<br />",$value);
printf("%X<br />",$value);
?>



Example: Displaying a number in binary format

 
<?php
    printf("The computer stores the number 42 internally as %b.",42);
?>



Format an integer and a floating-point value with the printf() function.

 
<?php
$i = 123456;
$f = 98765.567;
printf("\$i = %x and \$i = %b\n", $i, $i);
printf("\$i = %d and \$f = %f\n", $i, $f);
printf("\$i = %09d and \$f = %0.2f\n", $i, $f);
?>



Format strings for use in printf( )

 
Format               Meaning
 
%%                   A literal percent character; no matching parameter is required
 
%b                   Parameter is an integer; express it as binary
 
%c                   Parameter is an integer; express it as a character with that ASCII value
 
%d                   Parameter is a positive integer; express it as decimal
 
%f                   Parameter is a float; express it as a float
 
%o                   Parameter is an integer; express it as octal
 
%s                   Parameter is a string; express it as a string
 
%x                   Parameter is an integer; express it as hexadecimal with lowercase letters
 
%X                   Parameter is an integer; express it as hexadecimal with uppercase letters
<? 
    $number = 123;
    printf("123 in binary is: %b", $number);
    printf("123 in hex is: %h", $number);
    printf("123 as a string is: %s", $number);
    printf("%% allows you to print percent characters");

    $number = 123.456;
    $formatted = number_format($number, 2) . "\n";
    print "Formatted number is $formatted\n";
    printf("Formatted number is %.2f\n", $number);
?>



Formatting a price with printf()

 
<?
$price = 5; $tax = 0.075;
printf("The dish costs $%.2f", $price * (1 + $tax));
?>



int printf ( string format [, mixed argument [, mixed ...]] ) is the standard C way to format text

 
<?
    $animals = "lions, tigers, and bears";
    printf("There were %s - oh my!", $animals);
?>



Left-aligned by prepending a minus symbol (-) to the field width specifier

 
<?
    printf ("%-20s\n", "Left aligned");
?>



Padding Output with the Padding Specifier

 
<?
    printf("%04d", 36);
?>



Pad with leading zeroes:

 
<?
    $red = 1;
    $green = 1;
    $blue = 1;
    printf( "#%02x%02x%02x", $red, $green, $blue);
?>



printf and format

 
<?php
printf("$%01.2f", 43.2); 
printf("%d beer %s", 100, "bottles"); 
printf("%15s", "Some text");  
?>



printf() and sprintf() Formatting Types

 
Type       Description
%          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 American Standard Code for Information Interchange (ASCII) value.
d         The argument is treated as an integer and presented as a (signed) decimal number.
e         The argument is treated as scientific notation (for example, 1.2e+2).
u         The argument is treated as an integer and presented as an unsigned decimal number.
f         The argument is treated as a float and presented as a floating-point number (locale aware).
F         The argument is treated as a float and presented as a floating-point number (nonlocale aware). Available since PHP 4.3.10 and PHP 5.0.3.
o         The argument is treated as an integer and presented as an octal number.
s         The argument is treated 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 upper-case letters).



printf and string format

 
<?php
printf("The %2\$s likes to %1\$s", "bark", "dog"); // The dog likes to bark
printf("The %1\$s says: %2\$s, %2\$s.", "dog", "bark"); // The dog says: bark, bar.
?>



printf() and Type Specifiers

 
Specifier      Description
 
d              Displays an argument as a decimal number
 
b              Displays an integer as a binary number
 
c              Displays an integer as its ASCII equivalent
 
f              Displays an integer as a floating-point number (double)
 
o              Displays an integer as an octal number (base 8)
 
s              Displays an argument as a string
 
x              Display an integer as a lowercase hexadecimal number (base 16)
 
X              Displays an integer as an uppercase hexadecimal number (base 16)



@printf("

Maths: %d; English: %d; History: %d; Biology: %d.

\n"

 
<?php
  
  $scores = array(88, 75);
  @list($maths, $english, $history) = $scores;
  @printf("<p>Maths: %d; English: %d; History: %d; Biology: %d.</p>\n",$maths, $english, $history, $biology);
?>



printf puts the numbers into the string

 
<?php
printf("The computer stores the numbers 42, and 256 internally as %b and %b.",42,256);
?>



printf() Type Specifiers

 
Option     Value
 
%          A literal percent characters (takes no parameters)
 
b          Integer represented as a binary number (for example: 101110111)
 
c          Integer represented as the character corresponding to its ASCII value
 
d          Integer represented as a signed integer number
 
u          Integer represented as an unsigned number
 
f          Floating-point value
 
o          Integer represented as an octal value
 
s          String value
 
x          Integer value represented in hexadecimal notation (with lowercase characters)
 
X          Integer value represented in hexadecimal notation (with uppercase characters)



The printf function formats complex strings using a single expression.

 
<?php
    $n = 15.32;
    $log = log ($n); 
    printf ("log (%0.2f) = %.5f\n", $n, $log); 
?>



Use printf to output float numbers

 
$hamburger = 4.91235;
$milkshake = 1.12395;
$cola = .85;
$food = 123.123;
$tax = 1.075;
$tip = 1.16;
printf("%1d %9s at \$%.2f each: \$%.2f\n", 2, "Hamburger", $hamburger, 2 * $hamburger);
printf("%1d %9s at \$%.2f each: \$%.2f\n", 1, "Milkshake", $milkshake, $milkshake);
printf("%1d %9s at \$%.2f each: \$%.2f\n", 1, "Cola", $cola, $cola);
printf("%25s: \$%.2f\n", "Food and Drink Total", $food);
printf("%25s: \$%.2f\n", "Total with Tax", $food + $tax);
printf("%25s: \$%.2f\n", "Total with Tax and Tip", $food + $tax + $tip);



Using printf() to Format a List of Product Prices

 
<html>
<head>
<title>Using printf() to Format a List of Product Prices</title>
</head>
<body>
<?php
$products = array (
      "A"=>2.4,
      "B"=>4,
      "C"=>80.6
      );
print "<pre>";
printf ("%-20s%23s\n", "Name", "Price");
printf ("%"-43s\n", "");
foreach ( $products as $Key=>$val ) {
  printf ("%-20s%20.2f\n", $Key, $val);
}
print "</pre>";
?>
</body>
</html>



When you specify a color in HTML, you combine three hexadecimal numbers between 00 and FF.

 
<?
    $red = 204;
    $green = 204;
    $blue = 204;
    printf( "#%x%x%x", $red, $green, $blue);
?>



Working with printf()

 
<?
printf ("This is my number: %d", 55);
?>



Zero-padding with printf()

 
<?
$zip = "6520";
$month = 2;
$day = 6;
$year = 2007;
printf("ZIP is %05d and the date is %02d/%02d/%d", $zip, $month, $day, $year);
?>