Menu Close

How to convert a first character of each word in a string into uppercase in PHP?

ucwords

The ucwords() is an in-built function of PHP, which is used to convert the first character of each word to uppercase in a string. The ucwords() is supported by the PHP 4 and above versions. It takes a string as an input and converts the first character of each word of the string to uppercase. The other characters of the string remain the same.

Hint: Use the PHP ucwords() function

Syntax

ucwords($string, $separator) 

Parameters

$string (required): This is a mandatory parameter of this function which specifies a first character of each word in a string into uppercase.

$separator (optional) – It is an optional parameter of this function, which contains the words separator characters. It specifies a character that uses a separator for the words in the input string. By default these separator characters are:

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

Return Value

It returns converted first character of each word in a string into uppercase.

Example

You can use the PHP ucfirst() function to convert a first character of a string into uppercase. Let’s check out the following example to understand how this function actually works:

<?php
$my_str = 'learn, share and grow your coding skills';
echo ucwords($my_str);
?> 

Output

Learn, Share And Grow Your Coding Skills 

There are some other functions in PHP which are similar to the ucwords() function:

Related PHP functions

  • strtolower() – It converts a string into lowercase.
  • strtoupper() – It converts a string into uppercase.
  • lcfirst() – It converts the first character of a string into lowercase.
  • ucfirst() – It converts the first character of a string into uppercase.
Posted in PHP

You can also read...