Making Uppercase Words Automatically In PHP With UCWords

Foreword: Humans are lazy by nature; we hold this truth to be self-evident. Any function in PHP that is going to save us a bit of time down the road is well worth the time invested in as a result.

Ever since the release of PHP 4, we’ve had the ability to utilize a function that automatically converts a string to uppercase characters. This function, UCWords, has many uses that aren’t so obvious at first glance.

  1. Title Case – While not everyone runs their own news website or even a movie database, we use title case for things such as website titles and website links. You’ll note in your browser window that your very own LearnPHPOnline.com utilizes the UCWords function to capitalize the title string.
  2. Sanitizing Database Input – We are all familiar with the stereotypical Internet user that just has to leave the Caps Lock key on at all times to get their point across. Protection against LOUD TEXT is quite prevalent in forum systems. (Try putting in “TEST TITLE” in vBulletin and watch it magically get transformed into “Test Title” if the forum is running correct settings.)
  3. Meta Tags – While you don’t see it directly, search engines still look at meta tags to help formulate what a website is and what it has to offer. By setting the “Title” attribute to automatically create uppercase words, we can show the search engines how proper we are without risking carpal tunnel syndrome.
  4. Fixing User Input – Let’s say you run your own business, and you contact registered users via E-mail to gain leads. If the user signed up and didn’t capitalize their name properly, it’s going to look unprofessional sending an email to them with their name in lowercase. In this situation we could actually lose business due to a lack of proper programming.

What Does The PHP Function UCWords Do?

The UCWords function automatically capitalizes every word within a given string. The function is especially easy to use since it only accepts a single argument: the string you want to be forced into uppercase stance. We can see an example of the usage of ucwords below, in our news headline demonstration.

PHP UCWords Example Of Basic Title Casing

<?PHP

 $newsHeadline "breaking: man finds way to capitalize news headings automatically";

 echo ucwords($newsHeadline);

 //Returns: Breaking: Man Finds Way To Capitalize News Headings Automatically

?>

So far things look fairly simple. But what exactly constitutes a new word for the UCWords function? Technically defined, a new word is going to be a string of characters following a whitespace, so long as the string doesn’t begin with a number. What do you think would happen if we were to start a string with an integer? Would the next letter be capitalized? In the below example, we take the real-life Internet company 43Things.com into consideration.

PHP UCWords Example Of Strings Starting With An Integer

<?PHP

 $webpageTitle "43things.com";
 echo ucwords($webpageTitle);
 //Returns 43things.com

?>

Note that in this example, the T will not be forced into capitalization because the string begins with a number. If we were to separate the number and the letter with a space, carriage return, newline, tab, or form-feed, then the letter would indeed be capitalized.

If the UCWords function encounters a string that is already capitalized, the function will not act on the string in question. If, however, the user were to convert the entire string to lower case letters and then pass the result to the UCWords function, we get a result as seen in the below example.

PHP UCWords Example Of Basic Rules Of Operation

<?PHP

 $screamingText "THIS IS VERY LOUD TEXT"

 echo ucwords($screamingText);

//Returns: THIS IS VERY LOUD TEXT

 echo ucwords(strtolower($screamingText));
//Returns: This Is Very Loud Text

?>

Capitalizing Only Certain Words In A String With UCWords

If we were concerned with only capitalizing a certain part of a string, we could write up a quick function to ensure that words that are commonly not capitalized are ignored. In many headings you may notice prepositions such as “at” or “to” aren’t capitalized. The following function solves the problem by accepting only a single argument.

PHP UCWords Function For Returning Partially Capitalized String

<?PHP

    function smartcase($str) {
       return preg_replace(
            "/(?<=(?<!:|'s)\W)(A|An|And|At|For|In|Of|On|Or|The|To|With)(?=\W)/e",

            'strtolower("$1")',
            $str);

    }

echo smartcase(ucwords("the prepositions in a title can be excluded with this function!"));

//Output: The Prepositions in a Title Can Be Excluded with This Function!
?>

We could add other words to the ignore feature simply by editing the following line:

PHP UCWords Example Of Basic Title Casing

     (A|An|And|At|For|In|Of|On|Or|The|To|With)

Sanitize Database Input With A Function Using UCWords

One of the more practical uses for UCWords is to sanitize input when putting information into a database. You may have noticed that some forum systems such as vBulletin will automatically change your thread title into title case if it is in all-caps. (After all, who really likes to read a screaming title?) An example of how this is done can be seen below, by implementing another function.

PHP UCWords Example Of Sanitizing Input

<?PHP

function titleCase($string)
     {
     return ucwords(strtolower($string));

     }

$threadName "CHECK OUT THIS NEW PHP FUNCTION GUYS!";
echo titleCase($threadName);

//Returns: Check Out This New PHP Function Guys!

?>

Closing Comments

UCWords has quite a bit of use to the PHP development community. Other functions that are worthy of noting would be: StrToUpper() , StrToLower() , UCFirst() , and MB_Convert_Case(). Each of these functions are necessary as the Internet shifts to a more and more dynamic environment.

Bottom line: We can all thank technology for allowing us to reduce the wear and tear on our Shift keys.

Comments
  1. jesh
    June 18, 2009

    ucword() should turn “CHECK OUT THIS NEW PHP FUNCTION GUYS!” into “Check Out This New Php Function Guys!”

    Leave a reply
  2. Zachary Schuessler
    June 19, 2009

    @jest – That’s incorrect, actually. You need to make use of the strtolower() function first, and then apply the ucwords() function. Take a look at the PHP.net manual for confirmation.

    Leave a reply
  3. www.eerectors.com
    June 24, 2009

    good job

    Leave a reply
  4. earnest
    November 5, 2009

    How do you do that with a wordpress function like this

    i tried is <?php echo ucwords ();?>

    but it did not work. How should i do this

    Leave a reply
  5. Pankaj
    December 13, 2009

    ucwords(); is good function in php, i like this website because i got newthing from here

    Leave a reply
  6. Bob
    February 12, 2010

    What I think jesh meant to say is the last example, as written, would actually return “PHP” as “Php”.

    Leave a reply
  7. OBX
    February 18, 2010

    Is there any way to get around the 43things example? We are trying to use this function to scrub addresses that start like 123A TEST ST. Is there a way to change it to the 123A Test St?

    Leave a reply
  8. Jack
    June 8, 2010

    OBX – It works like a charm…consider your address variable was $title like below.

    $title = “123A TEST ST”;
    $title = strtolower($title);
    function smartcase($strtitle) {
    return preg_replace(
    “/(?<=(?<!:|'s)\W)(A|An|And|At|For|In|Is|Of|On|Or|The|To|With)(?=\W)/e",'strtolower("$1")',$strtitle);
    }
    $title = @smartcase(ucwords($title));
    echo "$title“;

    Leave a reply
Leave a Comment Below »
Your Name
Your Email Address
Your Comment