How to Make First Letter Uppercase and the Rest Lowercase in a PHP String?

To make the first letter of a PHP string uppercase and the rest lowercase, you can do the following:

  1. Make string lowercase (using strtolower());
  2. Capitalize only the first letter (using ucfirst()).

This would return a new string with first letter capitalized and all remaining characters in lowercase (regardless of the case in the original string). For example:

$str = "FOO BAR";
$capStr = ucfirst(strtolower($str));

echo $capStr; // "Foo bar"

This, of course, does not consider any grammar-specific capitalization rules (such as capitalizing the first letter at the start of each new sentence or after certain punctuations, etc.):

$str = "fOO BAR BAZ. Qux Qaz Quux.";
$capStr = ucfirst(strtolower($str));

echo $capStr; // "Foo bar baz. qux qaz quux."

As you can see in the example above, there are two sentences in the string, but only the first letter of the entire string is capitalized and all remaining words are converted to lowercase.

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.