萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 字串首字母大寫:ucfirst 與 ucwords 完整用法指南

前言

PHP 提供三個字串大小寫轉換函數:ucfirst()、lcfirst()、ucwords()。本文詳細說明其用法、差異、多語言支援與實務應用。

函數快速對照

函數功能範例輸入範例輸出
ucfirst()字串第一個字元大寫'hello world''Hello world'
lcfirst()字串第一個字元小寫'Hello World''hello World'
ucwords()每個單字首字母大寫'hello world''Hello World'
strtolower()全字串小寫'HELLO WORLD''hello world'
strtoupper()全字串大寫'hello world''HELLO WORLD'

基本用法示範

<?php
$str = "hello world";

// ucfirst:只影響第一個字元
echo ucfirst($str);        // Hello world
echo ucfirst("HELLO");     // HELLO(其餘不變)

// ucwords:每個單字首字母大寫
echo ucwords($str);        // Hello World
echo ucwords("HELLO WORLD"); // HELLO WORLD(其餘不變)
echo ucwords("hello-world"); // Hello-world(連字號不視為分隔)

// 組合使用:標準標題大小寫
$title = "the quick brown fox";
echo ucwords(strtolower($title)); // The Quick Brown Fox
?>

進階參數:自訂分隔符(PHP 5.4+)

<?php
$str = "hello|world|php";

// 預設分隔符:空白字元(空格、定位字元、換行等)
echo ucwords($str);           // Hello|world|php

// 自訂分隔符
echo ucwords($str, "|");      // Hello|World|Php
echo ucwords($str, "|-");     // 多重分隔符:以 | 或 - 分隔

// 實用:檔案名稱格式化
$filename = "my_document_file_name.txt";
echo ucwords($filename, "_."); // My Document File Name.Txt
?>

多語言支援(UTF-8 / 多位元組字元)

<?php
// PHP 7.0+ 內建函數已支援 UTF-8
echo ucfirst('中文測試');     // 中文測試(中文無大小寫,不變)
echo ucfirst('αβγ');          // Αβγ(希臘字母支援)
echo ucfirst('ß');            // ß(德語銳音 S,PHP 7.3+ 支援大寫 ẞ)

// ucwords 同樣支援
echo ucwords('hello 世界');   // Hello 世界

// 注意:某些語言大小寫規則複雜(如土耳其語 i/İ, ı/I)
// 需設定正確 locale
setlocale(LC_CTYPE, 'tr_TR.UTF-8');
echo ucfirst('istanbul');     // İstanbul(需系統支援 locale)
?>

實務應用場景

1. 使用者輸入正規化

function normalizeName(string $name): string {
    // 去除多餘空白、統一小寫、每單字首字大寫
    $name = trim($name);
    $name = preg_replace('/\s+/', ' ', $name); // 合併連續空白
    $name = strtolower($name);
    return ucwords($name);
}

echo normalizeName("  jOhN   doE  "); // John Doe

2. SEO 友善標題產生

function generateSlug(string $title): string {
    $title = ucwords(strtolower($title)); // 標準化大小寫
    $slug = strtolower($title);
    $slug = preg_replace('/[^a-z0-9\s-]/', '', $slug); // 移除特殊字元
    $slug = preg_replace('/\s+/', '-', $slug); // 空白轉連字號
    return trim($slug, '-');
}

echo generateSlug("PHP ucfirst & ucwords 完整指南!"); 
// php-ucfirst-ucwords-完整指南

3. CSS 類別名稱轉換

function toCssClass(string $name): string {
    // kebab-case
    return strtolower(preg_replace('/([a-z])([A-Z])/', '$1-$2', ucwords($name, '_')));
}

echo toCssClass('user_profile_setting'); // user-profile-setting
echo toCssClass('userProfileSetting');   // user-profile-setting

常見陷阱與注意事項

情況結果說明
ucwords("hello-world")Hello-world連字號非預設分隔符,需指定 ucwords($str, "-")
ucwords("O'Reilly")O'Reilly單引號後字母不會大寫
ucwords("McDonald")Mcdonald無法處理特殊大小寫規則
全大寫輸入不變需先 strtolower() 再 ucwords()
數字開頭不影響ucfirst("123abc") → "123abc"

效能比較

<?php
$str = str_repeat("word ", 10000); // 40KB 字串

$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";
// ucwords 通常快 2-3 倍(C 層實作)
?>

總結

  • ucfirst():單一字串首字大寫,適合句子開頭
  • ucwords():標題、名稱、標籤每單字首字大寫
  • 組合模式:ucwords(strtolower($str)) 為標準標題大小寫
  • 自訂分隔符:PHP 5.4+ 支援第二參數指定分隔字元
  • UTF-8 相容:PHP 7.0+ 完整支援多位元組字元
  • 特殊語言規則:需配合 setlocale() 或使用 mb_convert_case()
copyright © 萬盛學電腦網 all rights reserved