PHP ucwords() Function

Quick summary: The PHP ucwords() function capitalizes the first character of each word in a string.

PHP ucwords() Syntax

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

PHP ucwords() Basic examples

echo ucwords("hello world");
PHP
Output:
Hello World

Capitalizes the first letter of each word.

echo ucwords("hello-world", "-");
PHP
Output:
Hello-World

Uses a custom word separator.

PHP ucwords() Real-world usage

$title = "the lord of the rings";
echo ucwords($title);
PHP
Output:
The Lord Of The Rings

Formats titles for display.

PHP ucwords() Edge cases

echo ucwords("123 hello");
PHP
Output:
123 Hello

Only alphabetic characters are capitalized.

PHP ucwords() Common mistakes

Using ucwords with UTF-8 text

ucwords does not handle multibyte characters correctly.

Incorrect
echo ucwords("český jazyk");
Correct
echo mb_convert_case("český jazyk", MB_CASE_TITLE, "UTF-8");

Use mb_convert_case() for UTF-8 strings.

PHP ucwords() Frequently Asked Questions

What does ucwords() do in PHP?

ucwords() capitalizes the first character of each word in a string.

What is considered a word in ucwords()?

Words are separated by whitespace characters such as spaces, tabs, or newlines.

Does ucwords() modify the original string?

No, ucwords() returns a new string and does not modify the original variable unless reassigned.

Is ucwords() multibyte-safe?

No, ucwords() is not multibyte-safe. Use mb_convert_case() for UTF-8 strings.

Can ucwords() handle custom delimiters?

Yes, you can specify additional delimiters as the second parameter.

What is the difference between ucwords() and ucfirst()?

ucwords() capitalizes each word, while ucfirst() only capitalizes the first character of the string.

Does ucwords() affect existing uppercase letters?

No, ucwords() only ensures the first letter of each word is uppercase and does not change other characters.

Can ucwords() be used for names?

Yes, ucwords() is often used to format names and titles.

What happens if the string is empty?

ucwords() returns an empty string if the input string is empty.

Does ucwords() work with Unicode characters?

No, ucwords() may not correctly handle Unicode characters. Use multibyte-safe functions.

Can ucwords() handle arrays?

No, ucwords() works only on strings. Use array_map() for arrays.

What is a real-world use case of ucwords()?

ucwords() is commonly used to format titles, names, and headings for display.

PHP ucwords() Related PHP Functions