PHP - ucfirst() 函式



PHP 的 ucfirst() 函式用於將給定字串的第一個字元轉換為大寫。術語“大寫”指的是大寫字母字元,例如 A、B、C……Z。

即使字串包含多個單詞,此函式也只將給定字串中第一個單詞的第一個字元轉換為大寫。

例如,如果我們有字串“hi aman”,則結果字串將為“Hi aman”,而不是“Hi Aman”。

語法

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

ucfirst(string $str): string

引數

以下是此函式的引數:

  • str - 輸入字串。

返回值

此函式返回一個首字母大寫的字串。

示例 1

以下程式演示了 PHP ucfirst() 函式的使用:

<?php
   $str = "tutorialspoint";
   echo "The original string: $str";
   echo "\nThe resultant string: ";
   #using ucfirst() function
   echo ucfirst($str);
?>

輸出

上述程式產生以下輸出:

The original string: tutorialspoint
The resultant string: Tutorialspoint

示例 2

如果給定字串的第一個字元已經是大寫,則不會影響原始字串。

這是使用 PHP ucfirst() 函式的另一個示例。我們使用此函式將字串“Hello World”的第一個字元轉換為大寫:

<?php
   $str = "Hello World";
   echo "The original string: $str";
   echo "\nThe resultant string: ";
   #using ucfirst() function
   echo ucfirst($str);
?>

輸出

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

The original string: Hello World
The resultant string: Hello World
php_function_reference.htm
廣告