printf
(PHP 4, PHP 5)
printf — Выводит отформатированную строку
Описание
Выводит строку, отформатированную в соответствии с аргументом
format
.
Возвращаемые значения
Возвращает длину выведенной строки.
- addcslashes
- addslashes
- bin2hex
- chop
- chr
- chunk_split
- convert_cyr_string
- convert_uudecode
- convert_uuencode
- count_chars
- crc32
- crypt
- echo
- explode
- fprintf
- get_html_translation_table
- hebrev
- hebrevc
- hex2bin
- html_entity_decode
- htmlentities
- htmlspecialchars_decode
- htmlspecialchars
- implode
- join
- lcfirst
- levenshtein
- localeconv
- ltrim
- md5_file
- md5
- metaphone
- money_format
- nl_langinfo
- nl2br
- number_format
- ord
- parse_str
- printf
- quoted_printable_decode
- quoted_printable_encode
- quotemeta
- rtrim
- setlocale
- sha1_file
- sha1
- similar_text
- soundex
- sprintf
- sscanf
- str_getcsv
- str_ireplace
- str_pad
- str_repeat
- str_replace
- str_rot13
- str_shuffle
- str_split
- str_word_count
- strcasecmp
- strchr
- strcmp
- strcoll
- strcspn
- strip_tags
- stripcslashes
- stripos
- stripslashes
- stristr
- strlen
- strnatcasecmp
- strnatcmp
- strncasecmp
- strncmp
- strpbrk
- strpos
- strrchr
- strrev
- strripos
- strrpos
- strspn
- strstr
- strtok
- strtolower
- strtoupper
- strtr
- substr_compare
- substr_count
- substr_replace
- substr
- trim
- ucfirst
- ucwords
- vfprintf
- vprintf
- vsprintf
- wordwrap
Коментарии
Be careful:
printf ("(9.95 * 100) = %d \n", (9.95 * 100));
'994'
First %d converts a float to an int by truncation.
Second floats are notorious for tiny little rounding errors.
You can use this function to format the decimal places in a number:
$num = 2.12;
printf("%.1f",$num);
prints:
2.1
see also: number_format()
instead of writing a function to round off a float (let's call it 'x') accurately, it's much easier to add a small number to x and then truncate it...
For example: if you want to round off to the nearest integer, just add 0.5 to x and then truncate it. if x=12.6, then it would calculate 13.1, and truncate it to 13. If x=14.4, it would calculate 14.9 and truncate it to 14.
[Editor's Note: Or just use vprintf...]
If you want to do something like <?php printf('There is a difference between %s and %s', array('good', 'evil')); ?> (this doesn't work) instead of <?php printf('There is a difference between %s and %s', 'good', 'evil'); ?> you can use this function:
<?php
function printf_array($format, $arr)
{
return call_user_func_array('printf', array_merge((array)$format, $arr));
}
?>
Use it the following way:
<?php
$goodevil = array('good', 'evil');
printf_array('There is a difference between %s and %s', $goodevil);
?>
and it will print:
There is a difference between good and evil
To format a dollar value as in $123.00 that may otherwise look like $123 use this
print ('$'); // the dollar sign in front of our answer
printf ('%.2f',$price);
To provide a more user-friendly interface, you can use colors when printing text in the terminal.
p('Ordinary text.');
p('Warning: Check this out...', 'info');
p('Ops! Something went wrong.', 'error');
p('Yeah... done!', 'success');
function p($text, $style = '', $newLine = true) {
$styles = array(
'success' => "\033[0;32m%s\033[0m",
'error' => "\033[31;31m%s\033[0m",
'info' => "\033[33;33m%s\033[0m",
'Black' => "\033[0;30m%s\033[0m",
'Red' => "\033[0;31m%s\033[0m",
'Green' => "\033[0;32m%s\033[0m",
'Yellow' => "\033[0;33m%s\033[0m",
'Blue' => "\033[0;34m%s\033[0m",
'Purple' => "\033[0;35m%s\033[0m",
'Cyan' => "\033[0;36m%s\033[0m",
'Gray' => "\033[0;37m%s\033[0m",
'Graphite' => "\033[1;30m%s\033[0m",
'Bold Red' => "\033[1;31m%s\033[0m",
'Bold Green' => "\033[1;32m%s\033[0m",
'Bold Yellow' => "\033[1;33m%s\033[0m",
'Bold Blue' => "\033[1;34m%s\033[0m",
'Bold Purple' => "\033[1;35m%s\033[0m",
'Bold Cyan' => "\033[1;36m%s\033[0m",
'Bold White' => "\033[1;37m%s\033[0m",
'Bg Black' => "\033[40;1;37m%s\033[0m",
'Bg Red' => "\033[41;1;37m%s\033[0m",
'Bg Green' => "\033[42;1;37m%s\033[0m",
'Bg Yellow' => "\033[43;1;37m%s\033[0m",
'Bg Blue' => "\033[44;1;37m%s\033[0m",
'Bg Purple' => "\033[45;1;37m%s\033[0m",
'Bg Cyan' => "\033[46;1;37m%s\033[0m",
'Bg Gray' => "\033[47;1;37m%s\033[0m",
'Underscore' => "\033[4;37m%s\033[0m",
'Inverted' => "\033[7;37m%s\033[0m",
'Blink' => "\033[5;37m%s\033[0m",
);
$format = '%s';
if (isset($styles[$style])) {
$format = $styles[$style];
}
if ($newLine) {
$format .= PHP_EOL;
}
printf($format, $text);
}
A few things to note about printf:
1. The definition of specifier g (or G) is often wrongly stated as being "use e or f (or E or f), whichever results in the shorter string". The correct rule is given in the documentation and it does not always give this result.
2. For g/G/h/H, trailing zeros after the decimal point are removed (but not a zero just after the decimal point, in the e/E style).
3. g/G are locale-aware whether the e/E or f style is produced.
4. For b/o/x/X/u (that is, all integer styles except d) the result shown for negative values is the twos complement form of the number, 2**32 + v, where v is the (negative) value.