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

PHP 字串首字母大寫與單字首字母大寫:ucfirst 與 ucwords 詳解

     編輯:PHP 相關知識

前言

PHP 提供 ucfirst() 與 ucwords() 兩個內建函數處理字串大小寫轉換,常用於標題格式化、使用者名稱顯示等場景。本文詳細說明用法、差異與多語系注意事項。

函數語法與差異

基本使用範例

<?php
$str = "php string functions are easy to use.";

$sentence = ucfirst($str);
$title    = ucwords($str);

echo "ucfirst: $sentence\n"; // Php string functions are easy to use.
echo "ucwords: $title\n";    // Php String Functions Are Easy To Use.
?>

進階:自訂單字分隔符(PHP 5.4+)

<?php
// ucwords 第二參數指定分隔符字元清單
echo ucwords("hello|world|test", "|") . "\n"; // Hello|World|Test
echo ucwords("foo-bar-baz", "-") . "\n";      // Foo-Bar-Baz
?>

多語系與編碼注意事項

  • UTF-8 環境:PHP 7+ 內建函數支援 UTF-8 多位元組字元,中文標點不受影響。
  • 非 ASCII 字母:ucfirst('école') 正確返回 'École'(需正確 locale 設定)。
  • 全大寫/全小寫轉換:搭配 strtolower()、strtoupper() 使用:
    $title = ucwords(strtolower('PHP STRING FUNCTIONS')); // Php String Functions

常見誤區

  • ❌ 以為 ucwords 會處理縮寫(如 "php" -> "Php" 而非 "PHP"),需自行處理特定縮寫。
  • ❌ 對已含大寫字母的字串直接使用,結果可能不如預期,建議先 strtolower() 統一。

總結

ucfirst() 處理句首大寫,ucwords() 處理標題大寫,兩者配合 strtolower() 可產生標準化標題格式。希望本文對您的 PHP 程式設計有所幫助。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
函數功能範例輸入範例輸出
ucfirst($str)將字串第一個字元轉大寫"hello world""Hello world"
ucwords($str)將字串每個單字的第一個字元轉大寫"hello world""Hello World"