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" ) : stringBy 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);Output:
John Doe2) 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));Output:
Jane DoeIn 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";And you want to convert it to:
Alice O'ReillyIf you use the default delimiters, it won’t work as expected. for example:
<?php
$name = "alice o'reilly";
echo ucwords($name);Output:
Alice O'reillyTo 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'");Output:
Alice O'ReillyNote 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.
Thank you for your feedback!