前言
PHP 提供 ucfirst() 與 ucwords() 兩個內建函數處理字串大小寫轉換,常用於標題格式化、使用者名稱顯示等場景。本文詳細說明用法、差異與多語系注意事項。
函數語法與差異
| 函數 | 功能 | 範例輸入 | 範例輸出 |
| ucfirst($str) | 將字串第一個字元轉大寫 | "hello world" | "Hello world" |
| ucwords($str) | 將字串每個單字的第一個字元轉大寫 | "hello world" | "Hello World" |
基本使用範例
<?php
$str = "php string functions are easy to use.";
$sentence = ucfirst($str);
$title = ucwords($str);
echo "ucfirst: $sentence\n"; // Php string functions are easy to use.
echo "ucwords: $title\n"; // Php String Functions Are Easy To Use.
?>
進階:自訂單字分隔符(PHP 5.4+)
<?php
// ucwords 第二參數指定分隔符字元清單
echo ucwords("hello|world|test", "|") . "\n"; // Hello|World|Test
echo ucwords("foo-bar-baz", "-") . "\n"; // Foo-Bar-Baz
?>
多語系與編碼注意事項
常見誤區
- ❌ 以為
ucwords 會處理縮寫(如 "php" -> "Php" 而非 "PHP"),需自行處理特定縮寫。
- ❌ 對已含大寫字母的字串直接使用,結果可能不如預期,建議先
strtolower() 統一。
總結
ucfirst() 處理句首大寫,ucwords() 處理標題大寫,兩者配合 strtolower() 可產生標準化標題格式。希望本文對您的 PHP 程式設計有所幫助。
- 上一篇文章: PHP 讀取 CSV 並輸出 HTML 表格的完整範例
- 下一篇文章: PHP 將陣列匯出為 CSV 檔案的標準做法
Copyright ©
程式碼之家 All Rights Reserved