I have a string with improper capitalization scattered like below:

$str = "tHis iS a StRinG thAt NeEds ProPer CapiTilization";
$newStr = ucfirst($str);
echo $newStr;

How would I be able to capitalize the first letter of each word and lower case the incorrectly capitalized letters? I need the string to be fully title case.

I know I can change to lower and then use ucwords() but is there a shorter way to do this?

Solution 1

How would I be able to capitalize the first letter of each word and lower case the incorrectly capitalized letters?

ucwords() will capitilize the first letter of each word. You can combine it with strtolower() to first lowercase everything.

For example:

ucwords(strtolower('HELLO WORLD!')); // Hello World!

Solution 2

There is an earlier question where I have already suggested mb_convert_case(), but the sample text in that question is rather lackluster.

There is a single, native function that performs title-casing on multiple words in a string and it is multibyte-safe. This is an excellent solution because you don't need to prepare the string to be all lowercase before making the leading letter of all words uppercase.

Code: (Demo)

$string = "tHis iS a StRinG thAt NeEds ProPer CapiTilization";
echo mb_convert_case($string, MB_CASE_TITLE, 'UTF-8');

Output:

This Is A String That Needs Proper Capitilization

Laravel also offers a helper method that can be used: title().

use Illuminate\Support\Str;

$converted = Str::of('a nice title uses the correct case')->title();

// A Nice Title Uses The Correct Case

Source: https://laravel.com/docs/8.x/helpers#method-fluent-str-title

Solution 3

Yes, you can do it with two functions ucwords() and strtolower()

<?php
    $str = "tHis iS a StRinG thAt NeEds ProPer CapiTilization";
    $newStr = ucwords(strtolower($str));
    echo $newStr;
?>

Explanation:

strtolower() will make all your string to lower cased.

Now, applying ucwords() on resulting string will make first letter of every world capital which will produce the required output.