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

PHP 字串首字母大寫:ucfirst() 與 ucwords() 完整比較

     編輯:PHP 相關知識

前言

本文補充說明 ucfirst()(句首大寫)與 ucwords()(單字首大寫)的差異、參數細節與實務用法,避免常見誤用。

函數簽名(PHP 7.0+)

ucfirst(string $string): string
ucwords(string $string, string $separators = " \t\r\n\f\v"): string

核心差異表

進階範例

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

echo ucfirst($str) . "\n";  // Php string functions are easy to use.
echo ucwords($str) . "\n";  // Php String Functions Are Easy To Use.

// 自訂分隔符(PHP 5.4+)
echo ucwords("hello|world", "|") . "\n";      // Hello|World
echo ucwords("foo-bar-baz", "-") . "\n";      // Foo-Bar-Baz
echo ucwords("line1\nline2\nline3", "\n") . "\n"; // Line1\nLine2\nLine3
?>

搭配 strtolower() 統一格式

<?php
$messy = "PhP StRiNg FuNcTiOnS";
$clean = ucwords(strtolower($messy)); // Php String Functions
echo $clean;
?>

多語系注意

  • PHP 7+ 內建支援 UTF-8,ucfirst('école') 正確返回 'École'。
  • 若伺服器 locale 設定正確,setlocale(LC_CTYPE, 'zh_TW.UTF-8') 可改善中文環境下的字母判斷。

總結

ucfirst() 處理句首,ucwords() 處理標題,記得先 strtolower() 統一大小寫再套用,即可產生規範格式。希望本文對您的 PHP 程式設計有所幫助。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
特性ucfirst()ucwords()
作用範圍整個字串的第一個字元每個單字的第一個字元
單字分隔判定無(僅看字串開頭)依 $separators 參數(預設空白字元)
適用場景句子、段落首字大寫標題、人名、地名格式化