PHP - str_pad
Trieda
Metóda - str_pad
(PHP 4 >= 4.0.1, PHP 5, PHP 7)
str_pad() is used to pad a string to the requested length using
characters from the $pad_string parameter. If
$pad_string contains more than 1 characters, characters are
alternated.
<?php echo str_pad("hello", 28, "-|", STR_PAD_BOTH); ?>
The string can be padded from right (STD_PAD_RIGHT, default),
from left (STD_PAD_LEFT) or from both sides
(STD_PAD_BOTH).
If STD_PAD_BOTH is set and the number of chars to pad is odd,
the left padding is 1 character shorter then the right padding.
<?php echo str_pad("hello", 8, "_", STR_PAD_BOTH); ?>
If $pad_length is less or equal to the length of the input
string, the input string is returned unchanged.
Procedurálne
- function str_pad (int $pad_length, string $pad_string = ) : string
Parametre
| Názov | Dátový typ | Predvolená hodnota | Popis |
|---|---|---|---|
| $pad_length | int | The requested length of the output. If is shorter than the length of the original string, the original string is returned intact. | |
| $pad_string | string | The characters to be used as the padding. |
Mávratovej hodnoty
Vracia: string
Returns the padded input string.
Príklady
<?php echo str_pad("ITnetwork.cz", 20, "-"); // ITnetwork.cz-------- ?>
<?php echo str_pad("ITnetwork.cz", 20, "-", STR_PAD_LEFT); // --------ITnetwork.cz ?>
<?php echo str_pad("ITnetwork.cz", 20, "-", STR_PAD_BOTH); // ----ITnetwork.cz---- ?>
<?php echo str_pad("TOMAS", 40, "mynameis", STR_PAD_BOTH); ?>
<?php
echo "| " . str_pad("Income", 12) . "|" . str_pad(426, 20, " ", STR_PAD_LEFT) . " USD |\n";
echo "| " . str_pad("Expense", 12) . "|" . str_pad(-6952, 20, " ", STR_PAD_LEFT) . " USD |\n";
echo "| " . str_pad("Total", 12) . "|" . str_pad(-6526, 20, " ", STR_PAD_LEFT) . " USD |\n";
?>
Adding leading zeros to a number:
<?php
$rand = 456;
// We want to have a 6-digit number
echo str_pad($rand, 6, "0", STR_PAD_LEFT);
?>
