February 7th 2007
(1) PHP Lesson 3
Educational, Programming, Tutorials
In lesson 2 we touched on variables in PHP and how to create one and then change it via a number of processes. Today we’re going to use some of the functions that PHP provide which allow us to manipulate and query strings and that will most likely become very handy in the future.
If you wish to take a look at the functions it offers then head on over to the PHP Manual, specifically the string functions.
Lesson 3: String Functions
Last week we touched on how to find the length of a string using the strlen() function. Today we’re going to look at a few more functions and put them into a practical example. To find the length of a string all we have to do is employ this function as is shown here:
<?php
$five = strlen("mouse"); //$five’s value is 5
$word = “mousemat”;
$eight = strlen($word); //$eight’s value is 8
?>
Now we’re going to look at replacing characters or phrases within a string with something else. To do this in the simplest way we are going to use the str_replace() function. There’s several parameters to this function. This means that we have to provide more information within the functions. In this case the format is str_replace(string to search for, string to replace it with, string to search within).
$string = "Sunny Man’s Blog";
$string = str_replace("Man","Boy",$string); //replace ‘Man’ with ‘Boy’
echo $string; //displays Sunny Boy’s Blog
Later on when we get to talking about SQL and databases you’ll need to be able to encrypt strings. There are several different types of encryption available in PHP. All of them are simple enough to use but, as we will will discuss later on, knowing when to use the correct one is vital. First let’s take a look at the different types.
$password = md5("password");
echo $password; //5F4DCC3B5AA765D61D8327DEB882CF99
$password = sha1(”password”);
echo $password; //5BAA61E4C9B93F3F0682250B6CF8331B7EE68FD8
Both md5 and sha1 have their advantages and disadvantages but they’re both quick to generate and once stored in a variable, easy to remember. Say we wanted to take a raw password that was given to us by a form (we’ll cover this soon), replace the letter ‘i’ with ‘z’ and encrypt it for storage in a database, this is how we would do it:
<?php
$password = "birmingham";
$password = str_replace("i","z",$password);
$password = md5($password);
?>
This is the end of lesson 3. In the next lesson we’ll talk about taking variables from a form, collecting them and manipulating them in a real life situation. After than we’re going to put all we’ve learnt into a logging in script in lesson 5 which will introduce you to salts, database queries and some other stuff we will cover in lessons 6 to 10.
/images/9r_leaf.png)
[…] Previously we looked at some of the methods PHP offers to sort and manipulate strings and we specifically looked at str_replace() and encryption methods like md5() and sha1(). […]