Changing Case in PHP


The ability take strings of text and manipulate them is one of the essential abilities you need as a programmer. If a user enters details on your forms, then you need to check and validate this data. For the most part, this will involve doing things to text. Examples are: converting letters to uppercase or lowercase, checking an email address to see if all the parts are there, checking which browser the user has, trimming white space from around text entered in a text box. All of these come under the heading of string manipulation. To make a start, we'll look at changing the case of character.

Changing the Case of a Character

Suppose a you have a textbox on a form that asks users to enter a first name and surname. The chances are high that someone will enter this:

bill gates

Instead of this:

Bill Gates

So your job as a programmer is to convert the first letter of each name from lower to uppercase. This is quite easy, with PHP.

There's a script amongst the files you downloaded called changeCase.php. Open up this page to see the code.

It's just a textbox and a button. The textbox will already have "bill gates" entered, when you load it up. What we want to do is to change it to "Bill Gates" when the button is clicked. Here's the script that does that.


$full_name = 'bill gates';

if (isset($_POST['Submit1'])) {

$full_name = $_POST['username'];
$full_name = ucwords( $full_name );



The first line just makes sure that the lowercase version is placed into the textbox when the page loads:

$full_name = 'bill gates';

This is the line that we want to convert and turn in to "Bill Gates". The only line in the code that you haven't yet met is this one:

$full_name = ucwords( $full_name );

And that's all you need to convert the first letter of every word to uppercase! The inbuilt function is this:

ucwords( )

In between the round brackets, you type the variable or text you want to convert. PHP will take care of the rest. When the conversion is complete, we're storing it back into the variable called $full_name.

If you just want to convert the first letter of a string (for a sentence, for example), then you can use ucfirst( ) . Like this:

$full_ sentence = ucfirst( $full_ sentence );

To convert all the letters to either upper or lowercase, use these:

strtoupper( )
strtolower( )

Here's an example of how to use them:

$change_to_lowercase = "CHANGE THIS";
$change_to_lowercase = strtolower($change_to_lowercase);

$change_to_uppercase = "change this";
$change_to_uppercase = strtoupper($change_to_lowercase);

Again, the variable or text you want to change goes between the round brackets of the function. This is then assigned to a variable.


In the next part, we'll take a look at how to trim unwanted white space from your strings