ucwords() Uppercase the first character of each word in a string

ucwords() function capitalizes the first character of every word in a string which is good for titles.

The definition of a word is any string of characters that is immediately after a whitespace (space, form feed, newline, carriage return, horizontal tab, and vertical tab).




ucwords() prototype

string ucwords ( string $str )
This means that ucwords() accepts string and returns a string with the first character of each word capitalized, if that character is alphabetic. We could rewrite the above function definition in an easy to understandable way:
Explanation of ucwords() function definition
Function PartDescription
stringType of value this function returns, which is a string, in this case returns the first character capitalized of every word in the string.
ucwordsThe function name
stringParameter type, this function accepts only string data type
$strParameter name, a variable that holds the data

Syntax

ucwords($str)

Return Value

ucwords() function returns string with the first character of each word capitalized.

Examples

Example 1

<?php
    $str = 'i am php string';
    // uppercase first character of every word of string
    $UpperWord = ucwords($str);
    echo $UpperWord;
?>

The above code prints I Am Php String on browser screen.

Example 2

<?php
    $str = 'I AM PHP STRING';
    // uppercase first character of every word of string
    $UpperWord = ucwords($str);
    echo $UpperWord;
?>

The above code prints I AM PHP STRING on browser screen. Notice the above code? It didn't change the string because its already in uppercase. So you have to lowercase the entire string and then use ucwords function to uppercase first character of every word.
See the code below:

Example 3

<?php
    $aVariable = 'I AM PHP STRING';
    //lowercase entire string
    $str = strtolower($aVariable);
    
    // uppercase first character of every word of string
    $UpperWord = ucwords($str);
    echo $UpperWord;
?>

The above code prints I Am Php String on browser screen.

Contents and Related Tutorials

  1. Make string first's character uppercase
  2. Make string first's character lowercase
  3. Make a string lowercase
  4. Make a string uppercase
  5. Uppercase first character of each word in a string