PHP Ucwords (With Advanced Examples)

In this tutorial, we will be tackling the PHP ucwords function with advanced examples.

This will give you additional in-depth knowledge about the PHP built-in functions.

PHP is known for its flexibility in terms of its functions and features for web designing and development.

You can also review more about the PHP functions on this site as you stay tuned!

Why PHP ucwords is needed?

The reason why the PHP ucwords() function is needed is because it enables programmers to convert the string into a more formal format.

This is helpful in turning a piece of string information into a presentable and neat one by turning each of the first characters of the string into uppercase.

What is PHP ucwords?

PHP’s built-in ucwords() function is used to convert the first letter of each word in a string to uppercase.

The ucwords() function is supported by PHP versions 4 and higher.

As brief fact information about the PHP ucwords() function, the “UC” is short for “uppercase”.

This specifies that its main function is to turn the first character of every word in a string into uppercase.

Specifically, the function takes a string as input and changes the first letter of each word to uppercase while leaving the rest of the characters the same. 

Additionally, the PHP ucwords() function has related functions and they are as follows:

  • ucfirst() – It turns the first character of a string into uppercase. 
  • lcfirst() – This function can convert the first character of a string to lowercase. 
  • strtoupper() – Converts a string to uppercase. 
  • strtolower() – It can turn a string lowercase.

According to PHP documentation, ucwords – uppercase the first character of each word in a string.

Now let us have a deeper understanding of the function by knowing the following characteristics:

PHP ucwords – Syntax

ucwords( $string, $separator)  

The syntax of the function lets you have the proper implementation of it and let us have a discussion of its parameters.

Parameters

The PHP ucwords() function takes two parameters which are the $string and the $separator.

Let us discuss these parameters one by one.

String – The $string is a required parameter of the ucwords() function.

This is because this parameter specifies the string values to convert.

Separator – The $separator, on the other hand, is an optional parameter only and specifies the separator to put in the strings. Its character may be in form of the following:

  • White spaces
  • \t – tab
  • \n – newline
  • \r – carriage return
  • \f – form feed
  • \v – vertical tab

Next, let us familiarize ourselves with what are the possible values that the PHP ucwords() function can return.

Return Values

The ucwords() function changes the string by making the first letter of each word in the string uppercase.

As a result, it will return the changed string.

Example PHP ucwords program:

This time let us have some example programs to implement the PHP ucwords() function.

The first batch of our example will only show the simple way of using the function.

After finishing the simple examples below, we will have advanced examples to help you in dealing with complex scenarios.

This concept is to guide you and help you through difficult programs.

To start with, take a look at our first example below:

Example Program

<?php  
    $sample = "good day, welcome to IT source code.";  
    echo ucwords($sample);  
?> 

This example preps you with the simple implementation of the function.

As you can see, the function is able to convert every first letter of the words in a string.

Meaning to say, the ucwords() function is ideal for manipulating strings.

Output:

Good Day, Welcome To IT Source Code.

On the programs out[ut, it shows that the program returns the exact same content of the string but with the capitalized letter on each of the words in the string.

Therefore from the string content "good day, welcome to IT source code." as input, comes the Good Day, Welcome To IT Source Code. as an output.

You can clearly see the changes and proof of how the program executes the ucwords() function.

5 Advanced example program using ucwords

This time, let us have five advanced examples to express the PHP ucwords() function with complex programs.

The examples below will give you a deeper understanding of the function as you apply it in a more complex manner.

You can also use the following and try them on your computer to see if they really work.

Example 1:

So first, we will know how the basic program works by using ucwords() PHP function.

<?php
    $input_string = "itsourcecode, where source code is not a problem!";
    echo "Before: ". $input_string;
    echo '</br>';
    $result_string = ucwords($input_string);
    echo "After: ".$result_string;
?>

In this basic program, we will compare the input and the output to see the transformation of the string.

It will clarify the use of the function as well as inform you how the function will react if you use it in your project.

Output:

Before: itsourcecode, where source code is not a problem!
After: Itsourcecode, Where Source Code Is Not A Problem!

This output is proof of the function when implemented in a basic example program.

However, what might be its output when used to execute more complex programs? Let us have another example below.

Example 2

For the second example, let us have a program that will let us understand how the basic program works by using ucwords() with a delimiters PHP function.

<?php
    $input_string = "itsourcecode,-where-source|code|is|not|a|problem!";
    $result_string1 = ucwords($input_string);
    echo "Before: ".$result_string1;
    
    echo "</br>";
    
    $result_string2 = ucwords($input_string, "|");
    echo "After: ".$result_string2;
?>

As you can see in this example, we have a scenario where our example string has a separator character (|).

Now we will have two arguments where one is only implementing the ucwords() function while the other one includes the separator into that parameter.

Now let’s see how will this implementation executes the program.

Output:

Itsourcecode,|where|source|code|is|not|a|problem!
Itsourcecode,|Where|Source|Code|Is|Not|A|Problem!

Here the output $result_string1 is identical to $result_string2 except for the change in the first capital letter.

However, after using the separator "|" parameter, $result_string2 will provide the desired output – each letter in the string will change its first character to a capital letter, even after the separator.

Example 3

This example shows how to use the ucwords() method on arrays containing a list of names/strings by deleting the delimiters "–" and "\".

<?php
    //FUNCTION to implement ucwords() on arrays containing a list of names/strings.
    function ucname($string1) {
        $string1 =ucwords(strtolower($string1));
        foreach (array('-', '\'') as $parameters1) {
            if (strpos($string1, $parameters1)!==false) {
                $string1 =implode($parameters1, array_map('ucfirst', explode($parameters1, $string1)));
            }
        }
        return $string1;
    }
    ?>
    <?php
    //Trying out using array
    $names1 =array(
    'PRINCE-LY CESAR',
    'SHAQUILLE O\'NEAL',
    'MARY GRACE PATULADA',
    'gerick domaine g mabag',
    'jOsHuA jOhN e vAlLejErA'
    );
    //Here in $names1, you can add additional strings to your array as required.
    foreach ($names1 as $name1) {
        print ucname("{$name1}\n</br>");
    }
    //PRINTS:
    /*
    Prince-Ly Cesar
    Shaquille O'Neal
    Mary Grace Patulada
    Gerick Domaine G Mabag
    Joshua John E Vallejera
    */
?>

Therefore in the third example, the program shows you how to implement the function even with separators.

Now this will give you an idea of what to include in your program to push on executing the ucwords() function by deleting the separators.

Output:

Prince-Ly Cesar
Shaquille O'Neal
Mary Grace Patulada
Gerick Domaine G Mabag
Joshua John E Vallejera

Now we have a readable output with capitalized letters of each word. You can also see that the following data were actual names and they have separators as input.

Example 4:

This is a sample program for the ucwords() function.

This program includes these features:

  • Multibyte/bytes Compatability
  • It handles delimiters even when numerous are present.
<?php
    function ucwords_specific1 ($string1, $delimiters1 = '', $encoding1 = NULL) {
        if ($encoding1 === NULL){
            $encoding1 = mb_internal_encoding();
        }
    
        if (is_string($delimiters1)) {
            $delimiters1 =  str_split( str_replace(' ', '', $delimiters1));
        }
    
        $delimiters_pattern11 = array();
        $delimiters_replace11 = array();
        $delimiters_pattern21 = array();
        $delimiters_replace21 = array();
    
        foreach ($delimiters1 as $delimiter1) {
            $uniqid1 = uniqid();
            $delimiters_pattern11[]   = '/'. preg_quote($delimiter1) .'/';
            $delimiters_replace11[]   = $delimiter1.$uniqid1.' ';
            $delimiters_pattern21[]   = '/'. preg_quote($delimiter1.$uniqid1.' ') .'/';
            $delimiters_replace21[]   = $delimiter1;
        }
    
        // $return_string1 = mb_strtolower($string1, $encoding1);
        $return_string1 = $string1;
        $return_string1 = preg_replace($delimiters_pattern11, $delimiters_replace11, $return_string1);
        $words1 = explode(' ', $return_string1);
    
        foreach ($words1 as $index1 => $word1) {
            $words1[$index1] = mb_strtoupper(mb_substr($word1, 0, 1, $encoding1), $encoding1).mb_substr($word1, 1, mb_strlen($word1, $encoding1), $encoding1);
        }
    
        $return_string1 = implode(' ', $words1);
        $return_string1 = preg_replace($delimiters_pattern21, $delimiters_replace21, $return_string1);
        return $return_string1;
    }
?>

<?php
    mb_internal_encoding('UTF-8');
    $string1 = "THE WALRUS AND THE CARPENTER - shaquille o'neal - hELLO-woRlD";
    echo ucwords_specific1( mb_strtolower($string1, 'UTF-8'), "-'");
?>

Output:

The primary arguments of the preceding program are $string1, $delimeter1, $delimiters, and encoding. Delimeter/Delimeters are development parameters that are optional but essential.

The parameter that must be converted is the string.

The parameter encoding is used to determine the character encoding. If the parameter is not omitted, the internal characters encoding value/values are utilized.

Output:

The Walrus And The Carpenter - Shaquille O'Neal - Hello-World

Example 5

Example 5 will give you another insight into using the PHP ucwords() function with complex strings.

<?php
    //This php syntax is to know how ucwords() function delivers the output if separator/parameter is not used.
    $title1 = 'THE "WALRUS AND THE CARPENTER" WERE WALKING CLOSE AT HAND - (THEY WEPT LIKE ANYTHING TO SEE SUCH QUANTITIES OF SAND)'; //STRING declaration with strings
    echo ucwords(strtolower($title1)); // here strtolower will convert $title to all small letters
    // ucwords now will provides output like this:
    // The "walrus And The Carpenter" Were Walking Close At Hand - (they Wept Like Anything To See Such Quantities Of Sand)
    // so the below program makes it change to correct format
?>
<?php
    function my_ucwords($string1) {
        $noletters1='"([/'; //add some more elements if u like to add
        
        for($i=0; $i<strlen($noletters1); $i++) //loop to access all the characters which is listed in $noletters1 variable
        $string1 = str_replace($noletters1[$i], $noletters1[$i].' ', $string1);
        $string1=ucwords($string1); //here ucwords() function will do the task of completing the first character of the words into capital letters
        for($i=0; $i<strlen($noletters1); $i++)
        $string1 = str_replace($noletters1[$i].' ', $noletters1[$i], $string1);
        return $string1; //it will return the string value from the function.
    }
    
    echo '</br></br>';

    $title1 = 'THE "WALRUS AND THE CARPENTER" WERE WALKING CLOSE AT HAND - (THEY WEPT LIKE ANYTHING TO SEE SUCH QUANTITIES OF SAND)';
    echo my_ucwords(strtolower($title1));
?>

The explanation of this example and how this will produce an output was discussed in the comments of the program.

You can see how each of the declarations will contribute to the ucwords() function to display the desired output.

Output:

The "walrus And The Carpenter" Were Walking Close At Hand - (they Wept Like Anything To See Such Quantities Of Sand)

The "Walrus And The Carpenter" Were Walking Close At Hand - (They Wept Like Anything To See Such Quantities Of Sand)

This output shows the proof of the discussed example program above.

Example 6:

This is an example of the code below, which will convert all words save the first to small characters.

They shall be capitalized. Here, ucfirst() is utilized. It is also included in the ucwords() method.

<?php
$text1 = "Is this itsourcecode? do you know what is 'ucwords', right? \"ucwords\" is used in this example!";
preg_match_all('/[A-Za-z]+|[^A-Za-z]+/', $text1, $data1);
for ($i = 0; $i < count($data1[0]); $i++) {
$data1[0][$i] = ucfirst($data1[0][$i]);
}
$text1 = implode("", $data1[0]);
print $text1;
?>

Output:

Is This Itsourcecode? Do You Know What Is 'Ucwords', Right? "Ucwords" Is Used In This Example!

Summary

In summary, we have discussed the overall concept of PHP ucwords() functions.

As you read through its discussion, you can conclude that its primary purpose is to turn every first letter of words in the string into uppercase.

Additionally, you can also explore the related functions of ucwords() such as the ucfirst(), lcfirst, strtoupper() and the strtolower() functions.

They may not be pro to uppercase results but the concept is related because these functions deal with the element’s case sensitivities.

Lastly, if you want to learn more about unlink in PHP, please leave a comment below. We’ll be happy to hear it!

Leave a Comment