Posted by: Corey on: October 21, 2006
PHP doesn’t have a built in proper case string function, though it does have upper and lower case functions. This isn’t too big of a problem though, since we can build one that acts just like we want anyways!
If you just have a short phrase or word that needs to have the very first letter capitalized, we’ve got a nice and easy job. Here’s the code:
$string = strtolower($string);
$string = substr_replace($string, strtoupper(substr($string, 0, 1)), 0, 1);
That might look a bit messy if you don’t like putting things together all at once, so here’s the jist: On the first line we make the whole string lowercase since we don’t know if there were capital letters where they shouldn’t be. The most inner part of the second line (substr) pulls the first character from our string. Moving outwards, the next function makes it uppercase, then finally, we replace the first letter of our string with the new uppercase letter.
Now what if we wanted every word in the phrase capitalized? Simple.
$words = explode(” “, $string);
for ($i=0; $i<count($words); $i++) {
$s = strtolower($words[$i]);
$s = substr_replace($s, strtoupper(substr($s, 0, 1)), 0, 1);
$result .= “$s “;
}
$string = trim($result);
Here we split the phrase up based on each space character and then did the same as we did above, only for each word. Then we built it back together word by word.
UPDATE: I didn’t realize it, but the ucwords function in PHP will do just this.
ucwords(strtolower($string));