Archive for February, 2008

PHP Text Formatting, ucwords() ucfirst()

Posted in Programming on February 2nd, 2008 by Jason – Be the first to comment

While working on a website for my work, I needed to do more text formatting than I normally do. I needed the first letter of a user input word to be capitalized. By using the php functions ucwords() and ucfirst() I was able to get this accomplished.

There are a couple different ways to use these two functions. One is if you want to capitalize the first letter of the first word in a string. You would use this for a sentence. Or if you wanted to capitalize the first letter of every word in a string, possibly for a title. The following are a few example codes of how to implement these functions

//capitalize the first letter of a string
$string = 'hello, my name is sam.';
echo ucfirst($string);
//This will print the following:
//Hello, my name is sam.
//capitalize the first letter of each word in a string
$string = 'hello, my name is sam.';
echo ucword($string);
//This will print the following:
//Hello, My Name Is Sam.

While this works good there are a couple things that you can do to make sure that the text appears as you really want it to. In the first example we wanted the first letter capitalized in the sentence, maybe we did this because users were not capitalizing things and it looks better capitalized. In the previous case there is an assumption that is made, but easy to forget. We assumed that the user would type all lower case letters. Wouldnt the world be a better place if we never received emails/posts/comments etc that were not in ALL CAPS. To correct an all caps string is very easy.

//capitalize the first letter of an ALL CAPS string
$string = 'HELLO, MY NAME IS SAM.';
echo ucfirst(strtolower($string));
//This will print the following:
//Hello, my name is sam.
//capitalize the first letter of each word in a string
$string = 'HELLO, MY NAME IS SAM.';
echo ucword(strtolower($string));
//This will print the following:
//Hello, My Name Is Sam.

By using the strtolower() function you can eliminate the ALL CAPS messages that everyone loves, this will make you string into all lowercase letters like we had in the first example and the capitalize the first letter of the string or of each word in the string.

Post to Twitter Tweet This Post