首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 字串大小寫轉換函數完整速查表

     編輯:PHP 相關知識

函數對照表

函數說明範例輸入輸出結果
ucwords()每個單字首字母大寫'hello world!''Hello World!'
ucfirst()字串第一個字元大寫'hello world!''Hello world!'
lcfirst()字串第一個字元小寫'HelloWorld''helloWorld'
strtoupper()所有字母大寫'Hello World!''HELLO WORLD!'
strtolower()所有字母小寫'HELLO WORLD!''hello world!'

實用組合技巧

1. 標準化標題格式 (Title Case)

$title = 'tHe qUICK bROWN fOX';
$title = ucwords(strtolower($title)); // The Quick Brown Fox

2. 駝峰命名轉換

// 蛇形 轉 小駝峰 (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

3. 多位元組字串 (中文/日文) 處理

注意: 以上函數僅處理 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 內容。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved