13.09.2016 Views

PHP and MySQL Web Development 4th Ed-tqw-_darksiderg

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

120 Chapter 4 String Manipulation <strong>and</strong> Regular Expressions<br />

Testing String Length with strlen()<br />

You can check the length of a string by using the strlen() function. If you pass it a<br />

string, this function will return its length. For example, the result of code is 5:<br />

echo'strlen("hello");.<br />

You can use this function for validating input data. Consider the email address on the<br />

sample form, stored in $email. One basic way of validating an email address stored in<br />

$email is to check its length. By our reasoning, the minimum length of an email address<br />

is six characters—for example, a@a.to if you have a country code with no second-level<br />

domains, a one-letter server name, <strong>and</strong> a one-letter email address.Therefore, an error<br />

could be produced if the address is not at least this length:<br />

if (strlen($email) < 6){<br />

echo ‘That email address is not valid’;<br />

exit; // force execution of <strong>PHP</strong> script<br />

}<br />

Clearly, this approach is a very simplistic way of validating this information.We look at<br />

better ways in the next section.<br />

Matching <strong>and</strong> Replacing Substrings with String<br />

Functions<br />

Checking whether a particular substring is present in a larger string is a common operation.This<br />

partial matching is usually more useful than testing for complete equality in<br />

strings.<br />

In the Smart Form example, you want to look for certain key phrases in the customer<br />

feedback <strong>and</strong> send the mail to the appropriate department. If you want to send emails<br />

discussing Bob’s shops to the retail manager, for example, you want to know whether the<br />

word shop or derivatives thereof appear in the message.<br />

Given the functions you have already looked at, you could use explode() or<br />

strtok() to retrieve the individual words in the message <strong>and</strong> then compare them using<br />

the == operator or strcmp().<br />

You could also do the same thing, however, with a single function call to one of the<br />

string-matching or regular expression-matching functions.They search for a pattern<br />

inside a string. Next, we look at each set of functions one by one.<br />

Finding Strings in Strings: strstr(), strchr(), strrchr(),<br />

<strong>and</strong> stristr()<br />

To find a string within another string, you can use any of the functions strstr(),<br />

strchr(), strrchr(), or stristr().

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!