Tuesday 17 July 2018

Using PHP to Capitalize a Word or Sentence

Using PHP to Capitalize a Word or Sentence

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:

  1. $str = "this is the sentence to capitalize";  
  2. echo ucwords($str);  
  3.   
  4. // 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:

  1. $str = "THIS IS THE SENTENCE TO CAPITALIZE";  
  2. echo ucwords($str);  
  3.   
  4. // Outputs: THIS IS THE SENTENCE TO CAPITALIZE  
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:

  1. $str = "THIS IS THE SENTENCE TO CAPITALIZE";  
  2. echo ucwords(strtolower($str));  
  3.   
  4. // 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.

0 comments:

Post a Comment