PHP - ucwords() 函式



PHP 的 ucwords() 函式用於將字串中每個單詞的第一個字元轉換為大寫。術語“大寫”指的是字母表中的大寫字母,例如 A、B、C 和 Z。例如,如果我們有一個字串“hello”,則結果字串將為“Hello”。

如果每個單詞的首字母已經是大寫,則結果字串保持不變。

ucwords 函式代表“大寫單詞”。

語法

以下是 PHP ucwords() 函式的語法:

ucwords(string $str, string $sep = " \t\r\n\f\v"): string

引數

此函式接受一個引數,如下所述:

  • string - 輸入字串。
  • sep(可選) - 分隔符包含單詞分隔符字元。

返回值

此函式返回修改後的字串,每個單詞的第一個字元都大寫。

示例 1

以下是 PHP ucwords() 函式的基本示例:

<?php
   $str = "tutorials point";
   echo "The given string is: $str";
   echo "\nThe modified string: ";
   #using ucwords() function
   echo ucwords($str);
?>

輸出

以上程式產生以下輸出:

The given string is: tutorials point
The modified string: Tutorials Point

示例 2

以下是 PHP ucwords() 函式的另一個示例。我們使用此函式將給定字串“hELLO wORLD”中每個單詞的第一個字元轉換為大寫:

<?php
   $str = "hELLO wORLD";
   echo "The given string is: $str";
   echo "\nThe modified string: ";
   #using ucwords() function
   echo ucwords($str);
?>

輸出

執行上述程式後,將顯示以下輸出:

The given string is: hELLO wORLD
The modified string: HELLO WORLD

示例 3

如果將可選引數 sep 傳遞給此函式,它將在將每個單詞的第一個字母轉換為大寫後使用該分隔符連線單詞:

<?php
   $str = "hey|how|are|you";
   echo "The given string is: $str";
   $sep = "|";
   echo "\nThe given separator: $sep";
   echo "\nThe modified string: ";
   # Using ucwords() function
echo ucwords($str, $sep);
?>

輸出

以下是上述程式的輸出:

The given string is: hey|how|are|you
The given separator: |
The modified string: Hey|How|Are|You

示例 4

如果省略可選引數(分隔符)並且給定字串包含分隔符字元,則此函式將僅將第一個單詞的首字母轉換為“大寫”:

<?php
   $str = "welcome-to-tp";
   echo "The given string is: $str";
   echo "\nThe modified string: ";
   # Using ucwords() function
   echo ucwords($str);
?>

輸出

執行上述程式後,它會生成以下輸出:

The given string is: welcome-to-tp
The modified string: Welcome-to-tp

示例 5

如果每個單詞的首字母“已經”是大寫,則字串不會受到影響,並且會返回相同的字串:

<?php
   $str = "Hey! John";
   echo "The given string is: $str";
   echo "\nThe modified string: ";
   #using ucwords() function
   echo ucwords($str);
?>

輸出

以下是上述程式的輸出:

The given string is: Hey! John
The modified string: Hey! John
php_function_reference.htm
廣告