Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
PHP Programming With MySQL Second Edition.doc
Скачиваний:
0
Добавлен:
01.05.2025
Размер:
43.07 Mб
Скачать

The comparison operators actually compare individual charac-

ters according to their position in American Standard Code for

Information Interchange, or ascii, which are numeric represen-

tations of English characters. ASCII values range from 0 to 255.

Lowercase letters are represented by the values 97 (“a”) to 122 (“z”).

Uppercase letters are represented by the values 65 (“A”) to 90 (“Z”).

Because lowercase letters have higher ASCII values than uppercase

letters, the lowercase letters are evaluated as being “greater” than the

uppercase letters. For example, an uppercase letter “A” is represented

by ASCII value 65, whereas a lowercase letter “a” is represented by

ASCII value 97. For this reason, the statement "a" > "A" returns

a value of TRUE because the uppercase letter “A” has a lower ASCII

value than the lowercase letter “a.”

To sort a list of e-mail addresses:

1.

Reopen the PHPEmail.php script in your text editor.


Comparing Strings

2.

Add the following function immediately after the

validateAddress() function. The function uses a nested for

loop to order the elements in the $EmailAddresses[] array.

The conditional expression in the if statement uses the com-

parison operator to compare each array element.

function sortAddresses($Addresses) {

$SortedAddresses = array();

$iLimit = count($Addresses)-1; /* Set the upper

limit for the outer loop */

$jLimit = count($Addresses); /* Set the upper

limit for the inner loop */

for ($i = 0; $i<$iLimit; ++$i) {

$CurrentAddress = $Addresses[$i];

for ($j = $i+1; $j<$jLimit; ++$j) {

if ($CurrentAddress > $Addresses[$j]) {

$TempVal = $Addresses[$j];

$Addresses[$j] = $CurrentAddress;

$CurrentAddress = $TempVal;

}

}

$SortedAddresses[] = $CurrentAddress;

}

return($SortedAddresses);

}

155

3.

Add the following code immediately after the declaration of

the sortAddresses function. This code sorts the list and dis-

plays the sorted results as a string.

$SortedAddresses = sortAddresses($EmailAddresses);

$SortedAddressList = implode(", ", $SortedAddresses);

echo "<p>Sorted Addresses: $SortedAddressList</p>\n";

4.

Change the foreach statement to use $SortedAddresses

instead of $EmailAddresses. The foreach statement should

appear as follows:

foreach ($SortedAddresses as $Address) {

5.

Save the PHPEmail.php file, upload the file to the browser,

and then open the file in your Web browser by entering the

following URL:

http://<yourserver>/PHP_Projects/Chapter.03/Chapter/

PHPEmail.php. Figure 3-19 shows the output.


CHAPTER 3

Manipulating Strings

156

Figure 3-19

A sorted list of e-mail addresses

6.

Close your Web browser window.

In the next few sections, you will study additional functions that you

can use to compare strings in PHP.

String Comparison Functions

PHP provides many string comparison functions to determine a

wide variety of relationships between strings. Many are designed

for special purposes, but several are useful in a number of different

situations.

The comparison functions you will probably use most often are

strcasecmp() and strcmp(). The only difference between the

two is that the strcasecmp() function performs a case-insensitive

comparison of strings, whereas the strcmp() function performs a

case-sensitive comparison. Both functions accept two arguments rep-

resenting the strings you want to compare. It’s important to under-

stand that most string comparison functions base their comparisons

on the ASCII values at the first position where the characters in

the two strings differ. Once this first differing character position is

found, the ASCII value of the character in the first string argument

is compared with the ASCII value of the corresponding character

in the second string argument. If the ASCII value in the first string

argument is less than that of the second, the functions return a value

less than 0, usually –1. However, if the ASCII value of the character

in the second string argument is greater than the ASCII value of the

corresponding character in the first string argument, the functions

return a value greater than 0, usually 1. For example, consider the

following strcmp() function, which compares the strings “Dan” and

“Don”. Because the “a” in “Dan” has a lower ASCII value than the “o”

in “Don”, the function returns a value less than 0.


Comparing Strings

strcmp("Dan", "Don"); // returns a value < 0

In comparison, the following statement, which switches the “Dan”

and “Don” arguments, returns a value greater than 0:

strcmp("Don", "Dan"); // returns a value > 0

If both string values are equal, the strcmp() function returns a value

of 0, as in the following example:

strcmp("Don", "Don"); // returns 0

157

Keep in mind that the strcmp() function performs a case-sensitive

comparison of two strings. The following statement returns a value

less than 0 because the uppercase “D” in the first string has a lower

ASCII value than the lowercase “d” in the second string:

strcmp("Don", "don"); // returns a value < 0

In the special case in which all the corresponding characters in the

two strings are the same, but one string argument is shorter than the

other, the shorter string argument is considered to be less than the

longer one. The following statement returns a value greater than 0

because “Donald” is longer than “Don”:

strcmp("Donald", "Don"); // returns a value > 0

To perform a case-insensitive comparison of two strings, use the

strcasecmp() function, which converts the text in both strings

to lowercase before they are compared. The following statement

returns a value of 0 because it uses the case-insensitive strcasecmp()

function:

strcasecmp("Don", "don"); // returns 0

The strncmp() and strncasecmp() functions are very similar to

the strcmp() and strcasecmp() functions, except that you need

to pass a third integer argument representing the number of char-

acters you want to compare in the strings. The following code uses

the strncmp() function to compare the first three letters in two text

strings:

$FirstCity = "San Diego";

$SecondCity = "San Jose";

if (strncmp($FirstCity, $SecondCity, 3) == 0)

echo "<p>Both cities begin with 'San'.</p>";

To modify the sortAddresses() function so it uses the

strcasecmp() function instead of comparison operators to sort the

e-mail addresses in the e-mail script:

1.

Return to the PHPEmail.php script in your text editor.


CHAPTER 3

Manipulating Strings

2.

Modify the conditional expression in the if statement within

the sortAddresses() function so it uses the strcasecmp()

function instead of the comparison operator, as follows:

if (strcasecmp($CurrentAddress,$Addresses[$j]) > 0) {

3.

158

Save the PHPEmail.php file, upload it to the server, and then

open the file in your Web browser by entering the following URL:

http://<yourserver>/PHP_Projects/Chapter.03/Chapter/

PHPEmail.php. The results should still appear as shown

in Figure 3-19.

Close your Web browser window.

4.

Determining the Similarity of Two Strings

The

Levenshtein

distance is

named for

mathemati-

cian Vladimir Levenshtein,

who developed the algo-

rithm in 1965.

The similar_text() and levenshtein() functions are used to deter-

mine the similarity between two strings (known as the Levenshtein

distance). The similar_text() function returns the number of char-

acters that two strings have in common, whereas the levenshtein()

function returns the number of characters you need to change for

two strings to be the same. Both functions accept two string argu-

ments representing the values you want to compare.

The following code demonstrates how to use the two functions with

the names “Don” and “Dan”. Figure 3-20 shows the output.

$FirstName = "Don";

$SecondName = "Dan";

echo "<p>The names \"$FirstName\" and \"$SecondName\

" have " . similar_text($FirstName, $SecondName) .

" characters in common.</p>";

echo "<p>You must change " . levenshtein($FirstName,

$SecondName). " character(s) to make the names

\"$FirstName\" and \"$SecondName\" the same.</p>";

Figure 3-20

Checking the similarity of two names


Comparing Strings

Determining if Words Are Pronounced Similarly

You can use the soundex() and metaphone() functions to determine

whether two strings are pronounced similarly. Both functions return

a value representing how words sound. The soundex() function

returns a value representing a name’s phonetic equivalent, whereas

the metaphone() function returns a code representing an English

word’s approximate sound. For example, consider the last name of the

author of this book, Gosselin. The soundex() function returns a value

of “G245” for this string, whereas the metaphone() function returns

a value of “KSLN.” The following code uses the metaphone() function

to compare the name with an alternative spelling, “Gauselin”:

$FirstName = "Gosselin";

$SecondName = "Gauselin";

$FirstNameSoundsLike = metaphone($FirstName);

$SecondNameSoundsLike = metaphone($SecondName);

if ($FirstNameSoundsLike == $SecondNameSoundsLike)

echo "<p>The names are pronounced the same.</p>";

else

echo "<p>The names are not pronounced the same.</p>";

159

Because both versions of the name are pronounced the same way, the

preceding code displays “The names are pronounced the same.”

Although they perform the same type of function, the soundex() and

metaphone() functions cannot be used with each other because they

represent words with different kinds of values. To compare the name

“Gosselin” with the alternative spelling of “Gauselin,” you must com-

pare the values returned from two soundex() functions, as follows:

$FirstName = "Gosselin";

$SecondName = "Gauselin";

$FirstNameSoundsLike = soundex($FirstName);

$SecondNameSoundsLike = soundex($SecondName);

if ($FirstNameSoundsLike == $SecondNameSoundsLike)

echo "<p>The names are pronounced the same.</p>";

else

echo "<p>The names are not pronounced the same.</p>";

Short Quiz

1.

What is the difference between the strcasecmp() function

and the strcmp() function?

Why is the lowercase “a” considered to occur later in the

alphabet than the uppercase “A”?

Explain the difference between the similar_text() function

and the levenshtein() function.

2.

3.


CHAPTER 3

Manipulating Strings

Working with Regular Expressions

One of the more accurate ways of parsing strings involves regular

expressions, which are patterns that are used for matching and

manipulating strings according to specified rules. With scripting lan-

guages such as PHP, regular expressions are most commonly used for

validating submitted form data. For example, you can use a regular

expression to ensure that a user enters a date in a specific format, such

as mm/dd/yyyy, or a telephone number in the format (###) ###-####.

Most scripting languages support some form of regular expres-

sions. PHP supports Perl Compatible Regular Expressions (PCRE).

Table 3-2 lists some of the PCRE functions available in PHP.

Function

preg_match(pattern, string)

preg_match_all(pattern, string)

preg_replace(pattern,

replacement, string[, limit])

preg_split(pattern, string [, limit])

160

Description

Performs a search for a matching pattern

Performs a search for a matching pattern,

returns the number of matches found

Performs a replacement of a matching

pattern

Divides an input string into an array of strings

that are separated by a specified matching

pattern

Filters an input array and returns an array

of those elements that match the specified

pattern

Returns a string that is the input string with

any character that has special meaning for a

PCRE preceded by the escape character (\)

preg_grep(pattern, array)

preg_quote(string)

Table 3-2

PCRE functions

The most commonly used PCRE function is preg_match(). You pass

to the function a regular expression pattern as the first argument

and a string containing the text you want to search as the second

argument. The function returns a value of 1 if a specified pattern is

matched or a value of 0 if it’s not. The following code demonstrates

how to determine whether the $String variable contains the text

“course technology,” with lowercase letters. The code uses a case-

sensitive pattern by default, so the if statement displays “No match”

because the value in the $String variable includes uppercase initials.

$String = "Course Technology";

if (preg_match("/course technology/", $String))


Working with Regular Expressions

echo "<p>Match found</p>";

else

echo "<p>No match</p>";

In comparison, the following code displays “Match found” because it

uses a case-insensitive pattern modifier after the pattern:

$String = "Course Technology";

if (preg_match("/course technology/i", $String))

echo "<p>Match found</p>";

else

echo "<p>No match</p>";

161

The preceding examples were a simple demonstration of how to use

the preg_match() function. There is no point in using regular expres-

sion functions with the preceding examples because you can more

easily determine whether the two strings match by using the com-

parison operator (==) or a string comparison function. The real power

of regular expressions comes from the patterns you write.

Writing Regular Expression Patterns

A regular expression pattern is a symbolic representation of the rules

that are used for matching and manipulating strings. As an example

of a common regular expression, consider the following code:

if (preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+

(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $Email) ==0)

echo "<p>The e-mail address is not in a valid

format.</p>";

The preceding code uses the preg_match() function to determine

whether the $Email variable is in a valid format for an e-mail address.

If the preg_match() function returns a value of 0, an echo statement

displays an appropriate message. As you can see, the logic is straight-

forward: If the e-mail address doesn’t match the regular expression,

the message is displayed. The complex part of the code is the pattern

passed as the first argument to the preg_match() function.

Regular expression patterns are enclosed in delimiters. The first

character in the pattern string is considered the opening delimiter.

All characters after the opening delimiter are considered part of the

pattern until the next occurrence of the opening delimiter character,

called the closing delimiter. Any characters after the closing delimiter

are considered to be pattern modifiers.

Although you can use any character except a letter, number, or the

backslash as a delimiter character, the most common character is the

forward slash (/). If a forward slash is part of the search pattern, you

You can find

many types

of prewritten

regular

expressions

on the Regular Expression

Library Web page at

http://www.regexlib.com/.


Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]