str_pad
是 PHP 中的一個(gè)字符串處理函數(shù),它可以將一個(gè)字符串填充到指定的長度。這個(gè)函數(shù)非常有用,特別是在處理文本對齊、生成序列號(hào)或者格式化輸出時(shí)。以下是一些 str_pad
的實(shí)際應(yīng)用案例:
$text = "Hello";
$padded_text = str_pad($text, 10, " ", STR_PAD_RIGHT);
echo $padded_text; // 輸出 "Hello "
for ($i = 1; $i <= 5; $i++) {
$serial_number = str_pad($i, 4, "0", STR_PAD_LEFT);
echo "Serial Number: " . $serial_number . "\n";
}
// 輸出:
// Serial Number: 0001
// Serial Number: 0002
// Serial Number: 0003
// Serial Number: 0004
// Serial Number: 0005
$data = [
["name" => "Alice", "age" => 30],
["name" => "Bob", "age" => 25],
["name" => "Charlie", "age" => 22]
];
foreach ($data as $row) {
$name = str_pad($row["name"], 10, " ", STR_PAD_RIGHT);
$age = str_pad($row["age"], 3, " ", STR_PAD_LEFT);
echo "Name: " . $name . " Age: " . $age . "\n";
}
// 輸出:
// Name: Alice Age: 30
// Name: Bob Age: 25
// Name: Charlie Age: 22
這些示例展示了如何使用 str_pad
函數(shù)在不同場景中實(shí)現(xiàn)字符串的填充和格式化。