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

PHP 字串首字母大小寫轉換完整指南:ucfirst、ucwords、lcfirst、mb_* 多國語言支援

     編輯:PHP 相關知識

核心函式速查表

函式用途範例輸入範例輸出PHP 版本
ucfirst()字串第一個字元轉大寫'hello world''Hello world'4+
lcfirst()字串第一個字元轉小寫'Hello World''hello World'5.3+
ucwords()每個單字第一個字元轉大寫'hello world''Hello World'4+
strtolower()全字串轉小寫'HELLO WORLD''hello world'4+
strtoupper()全字串轉大寫'hello world''HELLO WORLD'4+
mb_convert_case()多位元組支援 (MB_CASE_TITLE/LOWER/UPPER)'hello 世界''Hello 世界'4.3+ (需 mbstring)

基本用法範例

<?php
// ucfirst: 只有最開頭字元大寫
echo ucfirst('hello world');      // Hello world
echo ucfirst('HELLO WORLD');      // HELLO WORLD (其餘不變)
echo ucfirst(strtolower('HELLO WORLD')); // Hello world (先全小寫再首大寫)

// lcfirst: 只有最開頭字元小寫
echo lcfirst('HelloWorld');       // helloWorld
echo lcfirst('HELLO WORLD');      // hELLO WORLD

// ucwords: 每個單字首字元大寫 (預設分隔: 空白、換行、tab)
echo ucwords('hello world');      // Hello World
echo ucwords('hello-world');      // Hello-world (連字號不視為分隔)
echo ucwords("hello\tworld\nfoo"); // Hello World Foo

// 自訂分隔字元 (PHP 5.4+)
echo ucwords('hello|world', '|'); // Hello|World

// 組合技:標題化 (Title Case) - 先全小寫再 ucwords
$title = 'THE QUICK BROWN FOX';
echo ucwords(strtolower($title)); // The Quick Brown Fox
?>

多國語言 / 多位元組字元支援 (mbstring)

標準函式 ucfirst/ucwords 僅處理 ASCII (單位元組)。中文、日文、韓文、表情符號等多位元組字元會導致錯誤結果。

<?php
// 錯誤示範
echo ucfirst('你好世界'); // 你好世界 (截斷多位元組字元)

// 正確:使用 mb_convert_case
echo mb_convert_case('你好世界', MB_CASE_TITLE, 'UTF-8'); // 你好世界 (中文無大小寫,但不會截斷)
echo mb_convert_case('hello 世界', MB_CASE_TITLE, 'UTF-8'); // Hello 世界

// MB_CASE_LOWER / MB_CASE_UPPER
echo mb_convert_case('HELLO 世界', MB_CASE_LOWER, 'UTF-8'); // hello 世界
echo mb_convert_case('hello 世界', MB_CASE_UPPER, 'UTF-8'); // HELLO 世界

// 自訂 mb_ucfirst / mb_ucwords 封裝
function mb_ucfirst(string $str, string $encoding = 'UTF-8'): string {
  $first = mb_substr($str, 0, 1, $encoding);
  $rest = mb_substr($str, 1, null, $encoding);
  return mb_strtoupper($first, $encoding) . $rest;
}

function mb_ucwords(string $str, string $separators = ' \t\r\n\f\v', string $encoding = 'UTF-8'): string {
  // PHP 5.4+ ucwords 已支援 $separators,但非多位元組安全
  // 簡易實作:依分隔字元切割、各自 mb_ucfirst、再組合
  $parts = preg_split('/([' . preg_quote($separators, '/') . '])/u', $str, -1, PREG_SPLIT_DELIM_CAPTURE);
  foreach ($parts as &$part) {
    if ($part !== '' && !str_contains($separators, $part)) {
      $part = mb_ucfirst($part, $encoding);
    }
  }
  return implode('', $parts);
}

// 測試
echo mb_ucfirst('你好世界'); // 你好世界
echo mb_ucwords('hello 世界'); // Hello 世界
?>

實務應用場景

1. 使用者名稱/姓名正規化

<?php
function normalizeName(string $raw): string {
  // 去除前後空白、多重空白合併
  $clean = preg_replace('/\s+/u', ' ', trim($raw));
  // 每個單字首字大寫 (支援中文姓名間空白)
  return mb_ucwords($clean);
}

echo normalizeName('  john   doe  '); // John Doe
echo normalizeName('王 小明'); // 王 小明
?>

2. 文章標題自動標題化

<?php
function toTitleCase(string $str): string {
  // 不變大寫的小詞 (英文)
  $smallWords = ['a','an','the','and','but','or','for','nor','on','at','to','from','by','in','of'];
  $words = explode(' ', mb_convert_case($str, MB_CASE_TITLE, 'UTF-8'));
  foreach ($words as &$w) {
    $lower = mb_strtolower($w, 'UTF-8');
    if (in_array($lower, $smallWords, true) && $w !== $words[0] && $w !== end($words)) {
      $w = $lower;
    }
  }
  return implode(' ', $words);
}

echo toTitleCase('the lord of the rings'); // The Lord of the Rings
echo toTitleCase('a tale of two cities'); // A Tale of Two Cities
?>

3. 程式碼命名風格轉換

<?php
// snake_case → camelCase
function toCamelCase(string $snake): string {
  return lcfirst(str_replace(' ', '', ucwords(str_replace('_', ' ', $snake))));
}
echo toCamelCase('user_profile_url'); // userProfileUrl

// PascalCase (StudlyCase)
function toPascalCase(string $snake): string {
  return str_replace(' ', '', ucwords(str_replace('_', ' ', $snake)));
}
echo toPascalCase('user_profile_url'); // UserProfileUrl

// kebab-case → snake_case
echo str_replace('-', '_', 'api-end-point'); // api_end_point
?>

效能與編碼注意事項

  • 編碼一致性:確保 PHP 檔案儲存為 UTF-8、mb_internal_encoding('UTF-8')、資料庫連線 SET NAMES utf8mb4。
  • 效能:ucfirst/ucwords 為 C 底層實作,極快。mb_* 函式較慢,但對多位元組字元正確。高頻呼叫可快取結果。
  • PHP 8.2+ 新函式:str_contains、str_starts_with、str_ends_with 可簡化判斷邏輯。

單元測試範例

<?php
use PHPUnit\Framework\TestCase;

class StringCaseTest extends TestCase {
  public function testUcfirst(): void {
    $this->assertEquals('Hello', ucfirst('hello'));
    $this->assertEquals('Hello', ucfirst('HELLO')); // 僅首字元
  }

  public function testLcfirst(): void {
    $this->assertEquals('hello', lcfirst('Hello'));
    $this->assertEquals('hELLO', lcfirst('HELLO'));
  }

  public function testUcwords(): void {
    $this->assertEquals('Hello World', ucwords('hello world'));
    $this->assertEquals('Hello|World', ucwords('hello|world', '|'));
  }

  public function testMbUcfirst(): void {
    $this->assertEquals('你好', mb_ucfirst('你好'));
    $this->assertEquals('Hello 世界', mb_ucfirst('hello 世界'));
  }

  public function testToCamelCase(): void {
    $this->assertEquals('userProfileUrl', toCamelCase('user_profile_url'));
    $this->assertEquals('apiEndPoint', toCamelCase('api_end_point'));
  }
}
?>

總結

PHP 提供豐富的字串大小寫轉換函式。核心原則:

  1. ASCII 專用:ucfirst/lcfirst/ucwords/strtolower/strtoupper 效能最佳。
  2. 多國語言:必須使用 mb_convert_case 或自訂 mb_ucfirst/mb_ucwords,避免多位元組字元截斷。
  3. 組合技:ucwords(strtolower(...)) 實現標準標題化;搭配小詞過濾可得出版品級 Title Case。
  4. 命名風格轉換:snake_case ↔ camelCase ↔ PascalCase ↔ kebab-case 皆可由上述基礎函式組合實現。

封裝成工具類 Str::title()、Str::camel() 等,可提升專案一致性與可維護性。

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