Home » PHP ucwords() Function

PHP ucwords() Function

by Online Tutorials Library

PHP String ucwords() Function

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.

Note: The ucwords() is a binary-safe function.

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

Related functions

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

Syntax

The syntax of the ucwords() function is given below that accepts two parameters.

The ucwords() returns the converted string whose first character of each word is converted to uppercase.

Parameters

$string (required) – It is a mandatory parameter of this function, which specifies the input string that needs to be converted.

$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 Values

The ucwords() function returns the modified string, where the first character of each word in a string is converted to uppercase.

Changelog

Version Description
5.4.32, 5.5.16 $separator parameter added by these versions.

Examples

There are some examples given, through which we can learn the working of the ucwords() function. Let’s see the below examples-

Example 1

Output:

Hello, My Name Is Lovyansh.  

Example 2

Output:

Before: Good morning! everyone.  After: Good Morning! Everyone.  

Example 3

Output:

In the above example, we have used “|” as a separator, which needs to be passed in ucwords() while modifying the string.

Good|morning!|everyone.  Good|Morning!|Everyone.  

Note: Doller $ symbol cannot be used as a separator, because $ is used before every variable in PHP. So, the program will generate an error “variable not found.”

You may also like