PHP ucwords

Created with Sketch.

PHP ucwords

Summary: in this tutorial, you’ll learn how to use the PHP ucwords() function to make the first character of each word in a string uppercase.

Introduction to the PHP ucwords() function

The ucwords() function accepts a string and returns a new string with the first character of each word converted to uppercase:

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

Code language: PHP (php)

By default, the ucwords() function uses the following characters to separate the words in a string:

To use different separators, you can specify them in the $separator argument.

Note that the ucwords() doesn’t modify the original string but returns a new modified string.

PHP ucwords() function examples

Let’s take some examples of using the ucwords() function.

1) Simple PHP ucwords() function example

The following example uses the ucwords() function to convert the first characters of the first name and last name to uppercase:

<?php

$name = 'john doe';

echo ucwords($name);

Code language: PHP (php)

Output:

John Doe

Code language: PHP (php)

2) Using PHP ucwords() function with the strtolower() function example

The ucwords() converts the first character of each word only. It doesn’t change other characters.

Therefore, you need to use th ucwords() with the strtolower() function to convert the strings. For example:

<?php

$name = 'JANE DOE';

echo ucwords(strtolower($name));

Code language: PHP (php)

Output:

Jane Doe

Code language: PHP (php)

In this example, the $name is in uppercase. The strtolower() function returns the lowercase version of the string. And the ucwords() returns a new string with the first character of each word converted to uppercase.

3) Using PHP ucwords() function with additional word delimiters

Suppose you have the following name:

$name = "alice o'reilly";

Code language: PHP (php)

And you want to convert it to:

Alice O'Reilly

Code language: PHP (php)

If you use the default delimiters, it won’t work as expected. for example:

<?php

$name = "alice o'reilly";
echo ucwords($name);

Code language: PHP (php)

Output:

Alice O'reilly

Code language: PHP (php)

To make it works, you need to add the character ' to the default separators like this:

<?php

$name = "alice o'reilly";
echo ucwords($name, " \t\r\n\f\v'");

Code language: PHP (php)

Output:

Alice O'Reilly

Code language: PHP (php)

Note that the default delimiters " \t\r\n\f\v" ensure the current logic for separating words are the same as before.

Summary

  • Use the PHP ucwords() to returns a new string with the first character of each word converted to uppercase.

Leave a Reply

Your email address will not be published. Required fields are marked *