前言
PHP 提供 ucfirst()(首字大寫)與 ucwords()(每單字首字大寫)兩個函數處理字串大小寫轉換。本文深入解析用法細節、多語言支援、常見陷阱與實務最佳實務。
函數對照表
| 函數 | 說明 | 範例 |
ucfirst($str) | 字串第一個字元大寫,其餘不變 | 'hello' → 'Hello' |
lcfirst($str) | 字串第一個字元小寫,其餘不變 | 'Hello' → 'hello' |
ucwords($str, $separators) | 每個單字首字元大寫,可自訂分隔符 | 'hello world' → 'Hello World' |
strtolower($str) | 全字串轉小寫 | 'HELLO' → 'hello' |
strtoupper($str) | 全字串轉大寫 | 'hello' → 'HELLO' |
mb_convert_case($str, MB_CASE_TITLE) | 多語言標題大小寫(Unicode 標準) | 支援特殊語言規則 |
基本用法示範
<?php
$string = "php string functions are easy to use.";
// ucfirst:只影響第一個字元
$sentence = ucfirst($string);
echo $sentence . "\n";
// Php string functions are easy to use.
// ucwords:每個單字首字元大寫
$title = ucwords($string);
echo $title . "\n";
// Php String Functions Are Easy To Use.
// 組合:標準標題大小寫(先全小寫,再每單字首字大寫)
$properTitle = ucwords(strtolower($string));
echo $properTitle . "\n";
// Php String Functions Are Easy To Use.
?>
自訂分隔符(PHP 5.4+)
<?php
$str = "hello|world|php|developer";
// 預設分隔符:空白字元(空格、tab、換行等)
echo ucwords($str); // Hello|world|php|developer
// 指定分隔符
echo ucwords($str, "|"); // Hello|World|Php|Developer
echo ucwords($str, "|-"); // 多重分隔符
// 實用:檔案路徑、CSS 類別、資料庫欄位名
$snake = 'user_profile_settings';
echo ucwords($snake, '_'); // User_Profile_Settings
$kebab = 'user-profile-settings';
echo ucwords($kebab, '-'); // User-Profile-Settings
?>
多語言與 UTF-8 支援
<?php
// PHP 7.0+ 內建函數已支援 UTF-8 多位元組字元
echo ucfirst('中文測試'); // 中文測試(中文無大小寫概念)
echo ucfirst('αβγδε'); // Αβγδε(希臘字母支援)
echo ucfirst('ß'); // ß → ẞ(德語銳音 S,PHP 7.3+)
// ucwords 同樣支援
echo ucwords('hello 世界 php'); // Hello 世界 Php
// 特殊語言規則需 locale 支援
// 土耳其語:i → İ, ı → I
setlocale(LC_CTYPE, 'tr_TR.UTF-8');
echo ucfirst('istanbul'); // İstanbul(需系統安裝 tr_TR locale)
// 更可靠:使用 mb_convert_case(Unicode 標準標題大小寫)
echo mb_convert_case('istanbul', MB_CASE_TITLE, 'UTF-8'); // İstanbul
echo mb_convert_case('σ finales', MB_CASE_TITLE, 'UTF-8'); // Σ Finales(希臘語 sigma 規則)
?>
常見陷阱與解決方案
| 情況 | 問題 | 解決方案 |
| 全大寫輸入 | ucwords('HELLO WORLD') → 'HELLO WORLD' | 先 strtolower() 再 ucwords() |
| 連字號/底線分隔 | 不視為單字邊界 | 指定分隔符:ucwords($str, "-_") |
| 縮寫詞保持大寫 | ucwords('php api') → 'Php Api'(期望 PHP API) | 需自訂函數或事後修正 |
| 所有格 's | ucwords("john's") → "John'S" | 需正則後處理:preg_replace('/\'S\b/', "'s", $result) |
| McDonald、O'Reilly 等特殊姓名 | 無法正確處理 | 使用專門姓名格式化庫或人工維護例外表 |
實務應用範例
1. 人名正規化
function normalizePersonName(string $name): string {
$name = trim($name);
$name = preg_replace('/\s+/', ' ', $name); // 合併空白
$name = mb_strtolower($name, 'UTF-8');
// 特殊前綴處理
$prefixes = ['van', 'von', 'de', 'da', 'di', 'le', 'la', 'du', 'mc', 'mac', "o'"];
$words = explode(' ', $name);
foreach ($words as &$word) {
$lower = mb_strtolower($word);
if (in_array($lower, $prefixes, true)) {
$word = $lower; // 保持小寫
} elseif (preg_match('/^[A-Z]\'$/i', $word)) {
// O'Reilly 類型
$word = mb_strtoupper($word[0]) . "'" . mb_strtolower(substr($word, 2));
} else {
$word = mb_convert_case($word, MB_CASE_TITLE, 'UTF-8');
}
}
return implode(' ', $words);
}
echo normalizePersonName("VAN GOGH"); // van Gogh
echo normalizePersonName("O'REILLY"); // O'Reilly
echo normalizePersonName("MC DONALD"); // Mc Donald
echo normalizePersonName(" JOHN DOE "); // John Doe
2. SEO 標題優化
function optimizeSeoTitle(string $title): string {
// 小連接詞不大寫
$minorWords = ['a', 'an', 'the', 'and', 'but', 'or', 'for', 'nor', 'on', 'at', 'to', 'from', 'by', 'in', 'of'];
$title = ucwords(mb_strtolower($title, 'UTF-8'));
$words = explode(' ', $title);
foreach ($words as &$word) {
$lower = mb_strtolower($word);
if (in_array($lower, $minorWords, true) && $word !== $words[0] && $word !== end($words)) {
$word = $lower;
}
}
return implode(' ', $words);
}
echo optimizeSeoTitle("THE LORD OF THE RINGS");
// The Lord of the Rings
3. 程式碼命名慣例轉換
function toPascalCase(string $str): string {
return str_replace(' ', '', ucwords(str_replace(['_', '-'], ' ', $str)));
}
function toCamelCase(string $str): string {
$pascal = toPascalCase($str);
return lcfirst($pascal);
}
function toSnakeCase(string $str): string {
return strtolower(preg_replace('/([a-z])([A-Z])/', '$1_$2', $str));
}
echo toPascalCase('user_profile'); // UserProfile
echo toCamelCase('user-profile'); // userProfile
echo toSnakeCase('UserProfile'); // user_profile
效能比較
<?php
$str = str_repeat("word ", 50000); // ~300KB
$start = microtime(true);
for ($i = 0; $i < 1000; $i++) ucwords($str);
echo "ucwords: " . (microtime(true) - $start) . "s\n";
$start = microtime(true);
for ($i = 0; $i < 1000; $i++) {
implode(' ', array_map('ucfirst', explode(' ', $str)));
}
echo "手動實作: " . (microtime(true) - $start) . "s\n";
$start = microtime(true);
for ($i = 0; $i < 1000; $i++) {
mb_convert_case($str, MB_CASE_TITLE, 'UTF-8');
}
echo "mb_convert_case: " . (microtime(true) - $start) . "s\n";
// ucwords 最快(C 實作),mb_convert_case 較慢但功能最完整
?>
總結
ucfirst():句子首字大寫
ucwords():標題、名稱每單字首字大寫,支援自訂分隔符
- 標準標題大小寫:
ucwords(strtolower($str)) 或 mb_convert_case($str, MB_CASE_TITLE)
- UTF-8 完整支援:PHP 7.0+ 內建函數可靠處理多位元組字元
- 特殊語言規則:使用
mb_convert_case() + 正確 locale
- 姓名/專有名詞:需額外邏輯處理前綴、縮寫、所有格等例外