PHP Chapter 7 (String Manipulation)

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.
<?PHP
$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 useucfirst( ) . 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.

Trim White Space in PHP

Another thing you'll want to do is to trim the white (blank) space from text entered into textboxes. This is quite easy, as there's some useful PHP functions to help you do this.
Suppose your user has entered this in the textbox:
" username "
From the quotation marks, we can see that there is extra space before and after the text. We can count how many characters this string has with another useful function: strlen( ). As its name suggests, this returns the length of a string, By length, we mean how many characters a string has. Try this script:
<?PHP
$space = " username ";
$letCount = strlen($space);
print $letCount;
?>
When you run the script, you'll find that the variable contains 14 characters. However, username has only 8 characters. If you're checking for an exact match, this matters!
To remove the white space, you can use the trim( ) function. Change your script to this:
<?PHP
$space = trim(" username ");
$letCount = strlen($space);
print $letCount;
?>
When you run the script now, you should find that the variable has the correct number of characters - 8. That's because the trim( ) function removes any blank spaces from the left and right of a string.
Two related function are ltrim( ) and rtrim( ). The first one, ltrim( ), removes space from the beginning of a string; the second one, rtrim( ), removes space from the end of a string. You can also use these two functions to trim unwanted characters, as we do much later in the book for the forum walkthrough.

Shuffle characters with PHP

A rather fun function you can use is str_shuffle( ). What this does is to shuffle all the characters in a string. You can use this to create a quick anagram programme. Try this script:
<?PHP
$full_name = 'anagram';
$full_name = str_shuffle($full_name);
print $full_name;
?>
Only three lines long, but the function takes a variable or direct text and shuffles the characters around.
Next up, something a little more useful - Finding one string inside of another.

The strpos function in PHP

A more useful thing you'll want to do is to see if one string is inside of another. For example, you can get which browser the user has with this:
$agent = $_SERVER["HTTP_USER_AGENT"];
print $agent;
Try it out and see what gets printed out. You should find that quite along string gets printed.
If you're testing which browser the user has, you can use a string function to search for a short string inside of this very long one. A PHP string function you can use is strpos( ). The syntax for the strpos function is:
strpos( string_to_search, string_to_find, start )
You need to supply at least the first two. The third, start, is optional. Here's a simple example.
$full_name = "bill gates";
$letter_position = strpos( $full_name, "b" );
print $letter_position;
When you run the script, a value of 0 is returned. That's because PHP considers the first character of the string to be at position 0, the second character at position 1, the third at position 2, etc. Since we were searching for the letter "b", and "bill gates" begins with this letter, a value of 0 is returned.
Try changing strpos( ) from this:
$letter_position = strpos($full_name, "b" );
to this:
$letter_position = strpos($full_name, "B" );
What happens when you run the script? Nothing! At least, you don't get a value back. That's because if strpos can't find your characters, it returns a value of false. A value of false in PHP can be tested for by using the triple equals operator. Like this:
$full_name = "bill gates";
$letter_position = strpos($full_name, "B");
if ($letter_position === false) {
print "Character not found " ;
}
else {
print "Character found";
}
The triple equals operator ( === ) not only checks for a value but what type of value it is: integer, string, Boolean, etc. If a string is not found, you need to use this operator, just in case the character you're searching for is at position 0. PHP is a little bit quirky with zeros. It seems them as having a false value as well. But it can be a different kind of false! So use ===.
Here's a script that checks which of two browsers a user has:
$agent = $_SERVER['HTTP_USER_AGENT'];
if ( strpos( strtoupper($agent), 'MSIE') ) {
print "Internet Explorer";
}
else if (strpos(strtoupper($agent), 'FIREFOX')) {
print "Firefox";
}
else {
print $agent;
}
The above script uses two of the string functions that you've met: strpos( ) and strtoupper( ). See if you can figure out what's going on!

Splitting a line of text in PHP

PHP allows you to split a line of text into its component parts. For example, if you were reading from a text file line by line you might have to break apart a line like this:
Poll number 1, 1500, 250, 150, 100, 1000
If this were a poll, and you want to display the results for all to see, then you might be trying to print something like this on the page:
Poll Number 1
Respondents: 1500
Answer A: 250
Answer B: 150
Answer C: 100
Answer D: 1000
The line of text is separated by commas. As the line is read in (which we'll see how to do in a later section), you'd be passing it to a variable. You'd then need to chop the text up, based on the comma. We can simulate that. First, pass the text to a variable:
$text_line = "Poll number 1, 1500, 250, 150, 100, 1000";
The next job is to split this text apart, so that PHP knows about all the separate pieces. The pieces we want are:
Poll number 1
1500
250
150
100
1000
To split lines of text, the gloriously sounding explode( ) function can be used. You just provided it with the text you want to split, and the character that is used to separate each piece. Here's the syntax:
explode( separator, string_to_split )
In between the round brackets of explode( ) the separator you want to use goes first, followed by a comma, then the string you want to split. For our line of code above, you'd do this:
$text_line = "Poll number 1, 1500, 250, 150, 100, 1000";
$text_line = explode( "," , $text_line );
So we're saying, "Look for a comma in the text, and split the line of text into separate pieces." Once PHP does its job, it puts all the parts into the variable on the left hand side of the equals sign ( = ), which was $text_line for us. This variable will then be an array!
To get at the pieces of the array, access it in the normal manner. Here's some code to try:
<?PHP
$text_line = "Poll number 1, 1500, 250, 150, 100, 1000";
$text_line = explode(",",$text_line);
print $text_line[0];
?>
Run the code and see what happens. Then change the 0 of the print statement to 1, then to 2, then to 3, then to 4, then to 5, and finally to 5. What happens when you enter 6 as the array Key number?
To see all the parts of your array, you can use a different form of print statement. Try changing the print line in your code from this:
print $text_line[0];
to this:
print_r($text_line);
Run your code and see what happens.
You should see your array details printed out, with all the Keys and the Values. The print_r( )statement is quite useful, when you're trying to debug your code.
And it does show that explode( ) works – all of the values are in an array!
Another way to access all the element returned by explode( ) is with a for loop:
$text_line = "Poll number 1, 1500, 250, 150, 100, 1000";
$text_line = explode(",",$text_line);
for ($start=0; $start < count($text_line); $start++) {
print $text_line[$start] . "<BR>";
}
In the for loop above, we set a start value to zero. The end condition is this:
$start < count($text_line)
We use the count( ) function to get the number of elements in the array called $text_line. Each time round the loop, PHP checks to see if the value in the variable called $start is less than how many elements are in the array. It breaks out of the loop when $start is NOT less than count($text_line).
Inside the loop, we have a normal print statement:
print $text_line[$start] . "<BR>";
To get at each element in the array, this is used:
$text_line[$start]
The variable called $start will be different each time round the loop. So the value at each position is printed. The "<BR>" at the end just adds a HTML line break.
As well as exploding a line of text, you'll need to know how to join the parts back together again.

Joining text in PHP

In the previous PHP lesson, you'll learnt how to split a line of text. All the parts of the line of text will then be in an array.
But if you have a line of text in an array, you can join it all together to form a single line of text. This is just the opposite of explode. This time, use implode( ):
$seasons = array("Autumn", "Winter", "Spring", "Summer");
$new_textline = implode( ",", $seasons );
Here we have an array called $seasons. The text in the array needs to be joined before writing it back to a text file. The implode( ) function does the joining. The syntax for the implode( ) function is just the same as explode( ).
implode( separator, text_to_join )
So implode( ) will join all the text together and separate each part with a comma, in the code above. Of course, you don't have to use a comma. You could use a dash:
$new_textline = implode("-", $seasons)
Or any other character:
$new_textline = implode("#", $seasons)
Even a space:
$new_textline = implode( " ", $seasons)
The implode( ) function can come in handy, if you need to work with single lines of text.

PHP and Escaping Characters

Escaping in PHP doesn't mean breaking free and "doing a runner". It is a technique to prevent PHP from ending your strings too early, or for making sure you have the correct string information returned. Here's an example. Try this script:
<?PHP
$string = 'John's Car';
print $string;
?>
Make sure you type the script exactly as it is, with all the single quote marks. Now run the script.
What you should find is that PHP gives you an error message. The reason is that you have three single quote marks. PHP gets confused, because it doesn't know what your string is. To solve the problem, you could use double quotes on the outside. Like this:
$string = "John's Car";
Or you could escape the apostrophe. You escape a character by typing a "slash" before it. Like this:
$string = 'John\'s Car';
If you try that out, you should find that the string prints correctly.
Now try this script:
<?PHP
$astring = 'mypath\';
print $astring;
?>
Again, you'll get an error from PHP. Surround it with double quotes instead of single quotes and run the script again. Does the string print?
The reason it doesn't is because you haven't escaped the slash. PHP sees it as a special character, and is expecting more details after the slash. But we want a slash in the string. To escape it, use another slash. Like this:
$astring = 'mypath\\';
So now we have two slashes on the end of the string. When you run the script, you should find that it prints out this:
mypath\
If your PHP script is not returning the characters it should do, then you may need to use the slash to escape them.
You also need to escape certain characters when working with databases, otherwise, you're opening yourself up to attack! You'll hear more on this topic when we get to that section.
In the next part, we'll have a list of string functions that may come in handy, and an example of how to use each one.

PHP String functions

Instead of detailing all the possible string functions you can use, we'll just give you a brief list. (There's loads of them!) There's an example of how to use each string function, if you click on the links below. Just dip in to them as and when needed.
chr( ) Converts an ASCII value to its equivalent character. For example, the ASCII value 64 is the @ symbol on a UK keyboard. If you want to disguise your email address, you could do it like this:
$email_address = "me" . chr(64) . "me.com";
print $email_address;

ord( ) Find out what the ASCII value of a character is with this string function. To see what ASCII value the @ symbol returns, you can use it like this:
$ascii_num = ord("@");
print $ascii_num;

echo( ) The PHP echo function can be used as an alternative to the print statement. These do the same thing:
$display_data = "something to display";
print $display_data;
echo $display_data;

similar_text( ) As it's name suggests, the PHP similar_text function tells you how similar two strings of text are. The syntax is:
similar_text( $string1, $string2, $percent )
The first two are the strings you want to compare. The percent tells you how accurate, in percentage terms, the match was. This is optional, though, so you can leave it out. Here's an example that tells the user how accurately they entered a username:
$real_username ="Bill Gates";
$user_attempt = "Bill Bates";
$check = similar_text($real_username, $user_attempt, $percent);
print($check) . "<BR>";
print($percent . "% correct");
The above script will print out the following:
9
90% correct
The blank space is counted as a character.

str_repeat( ) Repeats a character a specified number of times. If you want nine dollar signs, for example, then you'd use the str_repeat() function like this:
$extra_dollars = str_repeat( "$", 9 );
print $extra_dollars;

str_replace( ) The str_replace() function in PHP allows you to replace one string with another. The syntaxt is:
str_replace( $look_for, $change_to, $search_text, match_count );
The last one, match_count, is optional. It's counts how many matches it has found.
In the example below, we're looking for "explore" and want to replace it with "explode".
$search_text = "The explore function";
$look_for = "explore";
$change_to = "explode";
print $search_text . "<BR>";
$changed_text = str_replace($look_for, $change_to, $search_text);
print $changed_text;
So you're looking for one string in the search text, and replacing it with another.

str_word_count( ) The str_word_count() function tells you how many words a string has. The syntax is this:
str_word_count( string, return , char )
If all you want to know is how many words a string has, then you can leave out return, and char. In which case, you can use it like this:
$num_of_words = str_word_count("The word count function");
print $num_of_words;
The return value can be one of three numbers:
0 - How many words found. This is the default
1 - Brings back the words found as an array.
2 - Brings back the words found as an array, but the Keys change based on where in the string the words are found. Might be useful to someone!
The char option is if you want the function to consider any additional words to count.

strlen( ) To get the length of a string in PHP use the strlen function. The length is how many characters are in the string:
$string_length = strlen( "This is some text" );
The above line of code returns a value of 17 - the number of character and spaces in the string.

substr( ) This function is short for Substring. You can grab a number of character from a string with substr. For example, suppose you wanted to check if an email address ended in .com. You could grab the last few characters and check them with an if statement. The syntax for substr( ) is this:
substr( string, start, length )
So you provide the function with a string, then you have to tell PHP which character in the string to start at. The length is how many characters you want to grab. This is optional. If you miss it out, you'll grab all the characters to the end of the string.
Here's an example that checks an email address to see if ends in .com.
$email = "test@test.com";
$email_end = substr( $email, strlen($email) - 4 );
if ($email_end == ".com" ) {
print "ends in .com";
}
else {
print "doesn't end in .com";
}
Run the script and see which one prints out!
You can also start the search from the end of the string. In which case, provide a negative number. Try this new substr( ) line, in place of the one above:
$email_end = substr($email, -4, 4);
This time, we have a figure of minus four. This means "start 4 characters from the left of the end of the string. There's also a length number specified. This means "grab four characters from your starting position.
We'll look at some more string function in later section (date and time functions, and functions you can use for security purposes). But for now, let's take a closer look at what functions are, and how you can create your own in PHP.

Some more examples of string functions can be found on these external sites:
In the next section, we'll take a look at PHP Functions: what they are, and how to create your own.

Comments