Making a String Uppercase, Lowercase, or Capitalized

Aug 28, 2010 Author: Developer

One occasional problem with PHP is that MySQL supports case-insensitive character fields, but strings in PHP are case sensitive. In a query, MySQL makes no distinction between the words Ferrett, FERRETT, and FerReTt, but as strings in PHP, they have nothing in common. So in PHP you may need to change the case of characters in a string before you compare or print them.

PHP has three essential functions that convert string case: strtolower(), strtoupper(), and ucwords(). Here is a sample of them in action:

$string = "heY hOw arE yoU doinG?";
echo strtoupper($string);
// Displays "HEY HOW ARE YOU DOING?"

echo strtolower($string);
// Displays "hey how are you doing?"

echo ucwords(strtolower($string));
// Displays "Hey How Are You Doing?"
    The functions work as follows:
  • strtoupper() changes all of the characters in a string to uppercase.
  • strtolower() changes all of the words in a string to lowercase.
  • ucwords() converts the first letter of each word in a string to uppercase.

There are a few hitches with ucwords();the first is that it doesn't capitalize letters after a nonletter character, so a string like mrs. johnston-brown would become Mrs. Johnston-brown and ac/dc would be Ac/dc. If this bothers you, then you can create a function that uses regular expressions to explode the given string into an array of its individual words, then use ucwords() to capitalize each word, and finally join it back together into a single string.

A second concern is that ucwords() capitalizes certain words that shouldn't be capitalized, such as and, or, and a. If you want to use proper headline style, you can write a simple function that uses str_replace() to fix these words:

function fussy_capitalize($string) {
    // Uppercase, but leave certain words in lowercase
    $uppercase_words = array("Of ","A ","The ","And ","An ", "Or "); 
    $lowercase_words  = array("of ","a ","the ","and ","an ","or ");
    $string = ucwords(strtolower($string));
    $string = str_replace($uppercase_words, $lowercase_words, $string);
    // Uppercase the first word.
    return ucfirst($string);

Finally, if you're working with names, ucwords(strtolower()) eradicates preexisting capitalizations, so a name such as McMurdo becomes Mcmurdo. If it's very important that you preserve these cases, but you still need to compare strings in PHP, use strcasecmp(str1, str2), which ignores case when comparing str1 and str2.

views 10736
  1. Add New Comment