How to Use ucwords in PHP: Capitalize Words Easily
In PHP, use the
ucwords function to capitalize the first letter of each word in a string. Simply pass your string as an argument to ucwords, and it returns the modified string with each word's first letter in uppercase.Syntax
The ucwords function has a simple syntax:
ucwords(string $string, string $delimiters = " \t\n\r\0\x0B"): string
Here, $string is the input text you want to transform. The function returns a new string with the first letter of each word capitalized. Optionally, you can specify $delimiters to define word boundaries.
php
string ucwords(string $string, string $delimiters = " \t\n\r\0\x0B");Example
This example shows how ucwords capitalizes the first letter of each word in a sentence.
php
<?php
$text = "hello world from php";
$capitalized = ucwords($text);
echo $capitalized;
?>Output
Hello World From Php
Common Pitfalls
One common mistake is expecting ucwords to change letters beyond the first character of each word or to handle multibyte characters correctly. It only capitalizes ASCII letters at the start of words and does not modify the rest of the word.
Also, it treats any non-letter character as a word separator, so apostrophes or hyphens may not behave as expected.
php
<?php // Wrong: expecting all letters uppercase $text = "hello world"; echo ucwords($text); // Outputs: Hello World // Right: use strtoupper for all uppercase echo strtoupper($text); // Outputs: HELLO WORLD ?>
Output
Hello World
HELLO WORLD
Quick Reference
ucwords capitalizes the first letter of each word in a string.
- Input: string
- Output: string with capitalized words
- Does not change letters after the first character
- Does not support multibyte characters (use
mb_convert_casefor that)
Key Takeaways
Use
ucwords to capitalize the first letter of each word in a string.ucwords only affects the first character of each word and leaves the rest unchanged.It works best with ASCII characters and may not handle special characters or multibyte strings correctly.
For full uppercase, use
strtoupper instead.Remember that word boundaries are any non-letter characters, which can affect results with punctuation.