The ucwords()
function in PHP is used to convert the first character of each word in a string to uppercase, while the rest of the characters in the word remain lowercase. This function is useful when you want to format a string to have each word start with a capital letter, often seen in titles or headings.
Syntax:
string ucwords(string $string)
Parameters:
- $string: The input string to be converted.
Return Value:
- Returns a new string with the first character of each word converted to uppercase.
Example 1: Basic Example
<?php
$string = "hello world";
echo ucwords($string); // Output: Hello World
?>
Example 2: String with Multiple Words
<?php
$string = "this is a sample sentence";
echo ucwords($string); // Output: This Is A Sample Sentence
?>
Example 3: String with Punctuation
If the string contains punctuation, ucwords()
will still capitalize the first letter of each word, excluding punctuation marks as word boundaries.
<?php
$string = "hello, my name is john.";
echo ucwords($string); // Output: Hello, My Name Is John.
?>
Example 4: Custom Delimiters (Optional)
By default, ucwords()
uses spaces to determine where words begin. However, you can provide additional delimiters to treat as word boundaries using the second parameter.
<?php
$string = "hello-world-php";
echo ucwords($string, "-"); // Output: Hello-World-Php
?>
This function is great for formatting strings like titles or headings where each word should start with a capital letter.