Pulling Out Parts from a String

I l @ ve RuBoard

Earlier in this chapter you learned how to join strings together using concatenation. Besides making larger strings out of smaller pieces, you can also extract subsections of a string. There are a number of built-in functions that can do this in different ways, and I'll cover two here. The trick to using any method to pull out a subsection of a string is that you must know something about the string itself in order to do so effectively.

The strtok () function creates a sub-string, referred to as a token, from a larger string based upon a predetermined separator (a comma or a space, perhaps). For example, if you have users enter their full name in one field (presumably with their first and last names separated by a space), you could ascertain their first name with the code:

 $FirstName = strtok($Name, " "); 

where $Name is the name of the variable received from the form which contains the user 's full name. This line of programming tells PHP to pull out everything from $Name up until it finds a blank space. If you had the user enter their full name in the format of "LastName, FirstName", you could find their surname by writing:

 $LastName = strtok($Name, ","); 

Since you have wisely kept the two names distinct in your form, you will not need to use this function at this time.

A second way to pull out sections of a string is by referring to the indexed position of the characters within the string. When I refer to the index of a string, I mean the numerical location of a character, counting from the beginning. However, PHPlike most programming languagesbegins all indexes with the number 0. So to index the string "Larry," you would begin with the "L" at position 0, "a" at 1, "r" at 2, the second "r" at 3, and the "y" at 4. Even though the string length of "Larry" is 5, its index goes from 0 to 4. With this in mind, you can utilize the substr() function to create a sub-string based upon the index position of the sub-string's characters, like this:

 $SubString = substr($String,0,10); 

First, you must enter in the master string from which your sub-string will be derived (here, $String). Second, you indicate where the sub-string begins, as its indexed position (0so you want to start with the first character). Third, you determine how many characters, from that starting point, the sub-string is composed of (10). If, in this case, $String is not 10 characters long, the resulting $SubString will end with the end of $String.

Frequently you'll use the strlen() function to help determine the ending point of the string. This function calculates how long a string is (i.e., how many characters is contains) and is very easy to use:

 $StringLength = strelen($String); 

You'll use the notion of substr(), along with strlen(), and md5(), to write a nifty password generation program.

Passwords you use are more secure the more random they are. In fact, passwords which have no special meaning, are not based upon common words, and use a variety of upper- and lowercase letters and numbers are the most secure of all. This script will create a new, random password each time you reload the page.

To create a password generator in PHP:

  1. Start by creating a new PHP document in your text editor with the lines (Script 5.7):

     <HTML><HEAD><TITLE>Password   Generator</TITLE><BODY><?php $String = "This is the text which   will be encrypted so that we may   create random and more secure   passwords!"; 
    Script 5.7. It may seem like you took a couple of major jumps to get to this point, but the passwords.php script is just a useful conglomeration of what you've learned up until this point. And all in 15 lines!

    graphics/05sc07.jpg

    You can put any string here that you want, the specific text will not make a difference for our purposes. This text will be encrypted to create a more random string from which the password will be taken.

     $Length = 8; 

    By establishing your password length as a variable, you can simply change this one value to get different sized passwords. There is a limit of a password that is 32 characters long, which is the length of an encrypted string using md5().$String = md5($String);

    md5() is similar is use to crypt() but it will generate a string 32 characters long as opposed to crypt() which creates a string 12 characters long. . See the PHP manual or the PHP home page for more information on md5().

     $StringLength = strlen($String); 

    In order to extract a sub-string, you'll need to know the length of the encrypted string, so we use the strlen() function which returns how many characters are in the given string. Although you do know for a fact, that by using md5() the string length will always be 32, it's better to be safe, which is why you'll use the strlen() function. This way, should you change your methods at later date (using encrypt() instead of md5() for example), this line will still work properly.

     srand ((double) microtime() *  1000000); $Begin = rand(0,($StringLength -  $Length - 1)); 

    You need to determine the beginning point for your substr() function. The rand() function creates a random number between (and including) a minimum (here it is 0) and a maximum. (Remember to use the srand() line first or else you may not get truly random results from rand(). ) You have set your maximum to be the length of the string minus the length of the password minus one. Here's the reason why: if your encrypted string is 30 characters long and you require your passwords to be 8 characters long then the latest you can begin your substr() and still have an 8-character password is 21 (which refers to the 22nd character in the string, due to how indexing behaves). We put the calculation within parentheses for clarity sake, but rand() does not require it.

     $Password = substr($String, $Begin,   $Length); 

    The final step is to make a substr() call with your determined values. You are stating that the $Password variable is equal to a sub-string derived from the $String variable, beginning with indexed position $Begin, and continuing for $Length characters.

     print ("Your recommended password is:  <P><BIG>$Password </BIG>\n"); 

    Now print the results (emphatically).

  2. Close your PHP and HTML code with: ?></BODY></HTML>

  3. Save your script as passwords.php, upload it to your server, and test in your Web browser (Figures 5.17 and 5.18).

    Figure 5.17. The passwords.php page takes the work out of creating your own secure passwords.

    graphics/05fig17.gif

    Figure 5.18. Every time you reload the page, a new and different password will be delivered for the most part. (In actuality, due to the fact that md5() creates a 32-character string, there is a finite limit to the number of unique passwords this script will generate but it will create dozens of different passwords.)

    graphics/05fig18.gif

Tip

Instead of setting the $Length variable at the onset of our page, you could use the URL/GET trick to send the page a length value by appending ?Length=8 to the URL (if you do so, then be sure to remove line 7).


Tip

Databases have a date format which stores calendar dates as YYYY-MM-DD (or something similar to this). Since you would know the exact format of the string retrieved from the database, the sub-stringsyear, month, and daycould be calculated using substr():

 $Year = substr($Date,0,4); $Month = substr($Date,5,2); $Day = substr($Date,8,2); 

Tip

Using strlen() is definitely a situation where you absolutely do not want to write $Password = strlen($Password);, in which case you would replace the actual password value with a number indicating how many characters were once, but are no longer, in the variable !


I l @ ve RuBoard


PHP for the World Wide Web (Visual QuickStart Guide)
PHP for the World Wide Web (Visual QuickStart Guide)
ISBN: 0201727870
EAN: 2147483647
Year: 2001
Pages: 116
Authors: Larry Ullman

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net