| 函數 | 說明 | 範例輸入 | 輸出結果 |
|---|---|---|---|
ucwords() | 每個單字首字母大寫 | 'hello world!' | 'Hello World!' |
ucfirst() | 字串第一個字元大寫 | 'hello world!' | 'Hello world!' |
lcfirst() | 字串第一個字元小寫 | 'HelloWorld' | 'helloWorld' |
strtoupper() | 所有字母大寫 | 'Hello World!' | 'HELLO WORLD!' |
strtolower() | 所有字母小寫 | 'HELLO WORLD!' | 'hello world!' |
$title = 'tHe qUICK bROWN fOX'; $title = ucwords(strtolower($title)); // The Quick Brown Fox
// 蛇形 轉 小駝峰 (camelCase)
function toCamelCase($snake_str) {
return lcfirst(str_replace(' ', '', ucwords(str_replace('_', ' ', strtolower($snake_str)))));
}
echo toCamelCase('user_profile_id'); // userProfileId
// 小駝峰 轉 蛇形
function toSnakeCase($camel_str) {
return strtolower(preg_replace('/([a-z])([A-Z])/', '$1_$2', $camel_str));
}
echo toSnakeCase('userProfileId'); // user_profile_id
注意: 以上函數僅處理 ASCII 字母。中文字元不受影響,但若字串包含多位元組字元,請使用 mb_ 系列:
mb_convert_case($str, MB_CASE_UPPER, 'UTF-8'); // 全大寫 mb_convert_case($str, MB_CASE_LOWER, 'UTF-8'); // 全小寫 mb_convert_case($str, MB_CASE_TITLE, 'UTF-8'); // 標題格式 (每個單字首字母大寫)
ucwords() 不會將已大寫的字母轉小寫,必須先 strtolower()。lcfirst() 只影響第一個字元,其餘保持原樣。這些都是 C 底層實現的內建函數,效能極高。處理超大字串 (MB 級) 時,strtolower 比 mb_strtolower 快數倍,但僅限純 ASCII 內容。