前言
本文補充說明 ucfirst()(句首大寫)與 ucwords()(單字首大寫)的差異、參數細節與實務用法,避免常見誤用。
函數簽名(PHP 7.0+)
ucfirst(string $string): string
ucwords(string $string, string $separators = " \t\r\n\f\v"): string
核心差異表
| 特性 | ucfirst() | ucwords() |
| 作用範圍 | 整個字串的第一個字元 | 每個單字的第一個字元 |
| 單字分隔判定 | 無(僅看字串開頭) | 依 $separators 參數(預設空白字元) |
| 適用場景 | 句子、段落首字大寫 | 標題、人名、地名格式化 |
進階範例
<?php
$str = "php string functions are easy to use.";
echo ucfirst($str) . "\n"; // Php string functions are easy to use.
echo ucwords($str) . "\n"; // Php String Functions Are Easy To Use.
// 自訂分隔符(PHP 5.4+)
echo ucwords("hello|world", "|") . "\n"; // Hello|World
echo ucwords("foo-bar-baz", "-") . "\n"; // Foo-Bar-Baz
echo ucwords("line1\nline2\nline3", "\n") . "\n"; // Line1\nLine2\nLine3
?>
搭配 strtolower() 統一格式
<?php
$messy = "PhP StRiNg FuNcTiOnS";
$clean = ucwords(strtolower($messy)); // Php String Functions
echo $clean;
?>
多語系注意
- PHP 7+ 內建支援 UTF-8,
ucfirst('école') 正確返回 'École'。
- 若伺服器 locale 設定正確,
setlocale(LC_CTYPE, 'zh_TW.UTF-8') 可改善中文環境下的字母判斷。
總結
ucfirst() 處理句首,ucwords() 處理標題,記得先 strtolower() 統一大小寫再套用,即可產生規範格式。希望本文對您的 PHP 程式設計有所幫助。
- 上一篇文章: PHP 字串轉十六進位:bin2hex() 函數用法與應用場景
- 下一篇文章: PHP 字串大小寫轉換:strtolower() 與 strtoupper() 完整指南
Copyright ©
程式碼之家 All Rights Reserved