PHP 大小寫轉換

PHP 提供多個函數來轉換字串的大小寫。

strtolower() - 轉小寫

將字串中的所有字母轉換為小寫:

<?php
echo strtolower("Hello World");     // hello world
echo strtolower("HELLO WORLD");     // hello world
echo strtolower("HeLLo WoRLd");     // hello world
echo strtolower("Hello123World");   // hello123world
?>

strtoupper() - 轉大寫

將字串中的所有字母轉換為大寫:

<?php
echo strtoupper("Hello World");     // HELLO WORLD
echo strtoupper("hello world");     // HELLO WORLD
echo strtoupper("Hello123World");   // HELLO123WORLD
?>

ucfirst() - 首字母大寫

將字串的第一個字母轉換為大寫:

<?php
echo ucfirst("hello world");   // Hello world
echo ucfirst("HELLO WORLD");   // HELLO WORLD(其他字母不變)
echo ucfirst("hello World");   // Hello World
?>

首字母大寫,其餘小寫

<?php
$str = "hELLO WORLD";

// 先轉小寫,再首字母大寫
echo ucfirst(strtolower($str));  // Hello world
?>

lcfirst() - 首字母小寫

將字串的第一個字母轉換為小寫:

<?php
echo lcfirst("Hello World");   // hello World
echo lcfirst("HELLO WORLD");   // hELLO WORLD
?>

ucwords() - 每個單字首字母大寫

將每個單字的第一個字母轉換為大寫:

<?php
echo ucwords("hello world");         // Hello World
echo ucwords("hello world php");     // Hello World Php
echo ucwords("HELLO WORLD");         // HELLO WORLD(已經是大寫的不會改變)
?>

自訂分隔符

<?php
// 預設只以空格分隔
echo ucwords("hello-world");  // Hello-world

// 指定分隔符
echo ucwords("hello-world", "-");        // Hello-World
echo ucwords("hello-world_test", "-_");  // Hello-World_Test
?>

配合 strtolower

<?php
$str = "hELLO wORLD";

echo ucwords(strtolower($str));  // Hello World
?>

mb_* 多位元組版本

處理中文等多位元組字元時,應使用 mb_* 函數:

<?php
// 標準函數對 ASCII 字元有效
echo strtolower("ABC");  // abc

// 對於某些語言的特殊字元可能無效
echo strtolower("ÄÖÜÉ");  // 可能無法正確轉換

// 使用 mb_* 函數
echo mb_strtolower("ÄÖÜÉ", 'UTF-8');  // äöüé
echo mb_strtoupper("äöüé", 'UTF-8');  // ÄÖÜÉ
?>

mb_convert_case()

<?php
$str = "hello world";

// MB_CASE_UPPER - 全部大寫
echo mb_convert_case($str, MB_CASE_UPPER);  // HELLO WORLD

// MB_CASE_LOWER - 全部小寫
echo mb_convert_case($str, MB_CASE_LOWER);  // hello world

// MB_CASE_TITLE - 標題格式(每個單字首字母大寫)
echo mb_convert_case($str, MB_CASE_TITLE);  // Hello World
?>

常見應用

不區分大小寫的比較

<?php
function equalsIgnoreCase(string $a, string $b): bool {
    return strtolower($a) === strtolower($b);
}

var_dump(equalsIgnoreCase("Hello", "HELLO"));  // true
var_dump(equalsIgnoreCase("Hello", "World"));  // false
?>

格式化名稱

<?php
function formatName(string $name): string {
    return ucwords(strtolower(trim($name)));
}

echo formatName("  JOHN DOE  ");     // John Doe
echo formatName("jane smith");       // Jane Smith
echo formatName("ALICE JOHNSON");    // Alice Johnson
?>

生成 URL Slug

<?php
function slugify(string $text): string {
    $text = strtolower($text);
    $text = preg_replace('/[^a-z0-9]+/', '-', $text);
    return trim($text, '-');
}

echo slugify("Hello World!");    // hello-world
echo slugify("PHP Programming"); // php-programming
?>

生成常數名稱

<?php
function toConstantName(string $str): string {
    $str = strtoupper($str);
    $str = preg_replace('/[^A-Z0-9]+/', '_', $str);
    return trim($str, '_');
}

echo toConstantName("max file size");  // MAX_FILE_SIZE
echo toConstantName("api-key");        // API_KEY
?>

駝峰式轉換

<?php
// 蛇底式 → 駝峰式
function snakeToCamel(string $str): string {
    return lcfirst(str_replace('_', '', ucwords($str, '_')));
}

echo snakeToCamel("user_name");       // userName
echo snakeToCamel("first_last_name"); // firstLastName

// 駝峰式 → 蛇底式
function camelToSnake(string $str): string {
    return strtolower(preg_replace('/[A-Z]/', '_$0', lcfirst($str)));
}

echo camelToSnake("userName");        // user_name
echo camelToSnake("firstLastName");   // first_last_name
?>

標題格式化

<?php
function titleCase(string $str): string {
    // 小寫單字(介系詞、冠詞等)
    $smallWords = ['a', 'an', 'the', 'and', 'but', 'or', 'for', 'nor', 
                   'on', 'at', 'to', 'from', 'by', 'of', 'in'];
    
    $words = explode(' ', strtolower($str));
    
    foreach ($words as $i => &$word) {
        // 第一個單字或非小寫單字都要大寫
        if ($i === 0 || !in_array($word, $smallWords)) {
            $word = ucfirst($word);
        }
    }
    
    return implode(' ', $words);
}

echo titleCase("the quick brown fox");
// The Quick Brown Fox

echo titleCase("a tale of two cities");
// A Tale of Two Cities
?>

Email 正規化

<?php
function normalizeEmail(string $email): string {
    return strtolower(trim($email));
}

echo normalizeEmail("  USER@EXAMPLE.COM  ");  // user@example.com
?>

效能比較

<?php
$str = str_repeat("Hello World ", 10000);

// 這些函數都很快
$start = microtime(true);
$result = strtolower($str);
$time1 = microtime(true) - $start;

$start = microtime(true);
$result = strtoupper($str);
$time2 = microtime(true) - $start;

// 通常只需幾毫秒
?>

注意事項

<?php
// 這些函數不會修改原字串
$str = "Hello";
strtolower($str);
echo $str;  // "Hello"(不變)

// 需要賦值
$str = strtolower($str);
echo $str;  // "hello"

// 只影響字母
echo strtolower("Hello123!@#");  // hello123!@#
?>