How to Capitalize First Letter of Each Word in a String in PHP
To capitalize each word in a string in PHP, use the native ucwords()
function. Pass the string to modify as the first argument and store the result in a variable.
$string = 'This is a sentence of text.';
$output = ucwords($string);
print($output);
This Is A Sentence Of Text.
ucwords()
will only change the casing of the first character of each word in the string. If you're dealing with random mixed casing, you may want to convert all the characters to lower case using the PHP strtolower()
function before using ucwords()
to ensure proper formatting in the output like this:
$string = 'ThiS is a sEnteNce of teXt.';
$output = ucwords(strtolower($string));
print($output);
This Is A Sentence Of Text.