Using PHP to Capitalize a Word or Sentence

May 15th, 2011 - Posted by Steve Marks to PHP, Web Development.

If you’re the webmaster of a site that gathers user’s information you’ll probably know all too well that user input can be, to put it blutently, a bit sloppy. This isn’t a problem as such, but can look a bit improper when this information is shared or displayed to other users.

Aside from spelling mistakes and unnecessary whitespace, another common trend I see is people either entering data in all lowercase or uppercase letters. As a result, and to help formalize this user contributed information, today I wanted to discuss how we can correctly capitalize a word or sentence using a couple of PHP functions.

The ucwords() PHP Function

The primary PHP function we’ll be using is ucwords(). The ucwords() function converts the first character of each word in a string to uppercase. Lets take a look at it in action:

$str = "this is the sentence to capitalize";
echo ucwords($str);

// Outputs: This Is The Sentence To Capitalize

OK great, the first letter of every word is now a capital. This is fine, however let’s take a look at the following scenario:

echo ucwords($str);


Not what you expected? Let me explain… The ucwords() function only amends the first letter of every word and doesn’t touch the rest of the letters. Let me introduce the second function that we need to get this to work successfully; strtolower().

Using both functions together we can convert the entire string to lower case first, then capitalize it after. I’ve included an example below to demonstrate this:

echo ucwords(strtolower($str));

// Outputs: This Is The Sentence To Capitalize

Now that’s more like it!

NB: Be careful when performing the above updates to user’s input. If a word should infact be lower case or uppercase, contains a hyphen (-) or is made up of initials you might be presented with the incorrect results.

Tags: ,
This entry was posted on Sunday, May 15th, 2011 at 2:39 pm by +Steve Marks and is filed under PHP, Web Development. You can follow any responses to this entry through the RSS 2.0 feed.

Fear not, we won't publish this

Comments (0)

No comments have been left yet. Be the first