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

Working with Multiple Strings

Short Quiz

1.

What string function would you use to determine the number

of characters in a password that a user has entered?

What string function would you use to determine if an essay

keyed in a <textarea> form input field exceeds the maximum

number of words allowed?

What two string functions could be used to convert the case

of text strings to all uppercase or all lowercase letters?

141

2.

3.

Working with Multiple Strings

PHP provides many functions for splitting a string into substrings,

merging multiple strings, and changing one string based on another.

In this section, you will study basic techniques for working with more

than one string.

Finding and Extracting Characters

and Substrings

When applied to text strings, the term parsing refers to the act of

dividing a string into logical component substrings or tokens. This is

essentially the same process as the parsing (rendering) that occurs in

a Web browser when it extracts the necessary formatting informa-

tion from a Web page before displaying it on the screen. In the case

of a Web page, the document itself is one large text string from which

formatting and other information needs to be extracted. However, at

a programming level, parsing usually refers to the extraction of infor-

mation from string literals and variables.

In some situations, you will need to find and extract characters and

substrings from a string. For example, if your script receives an e-mail

address, you may need to extract the name portion of the e-mail

address or domain name. Several functions in PHP allow you to find

and extract characters and substrings from a string.

There are two types of string search and extraction functions: func-

tions that return a numeric position in a text string and those that

return a character or substring. Both functions return a value of

FALSE if the search string is not found. To use functions that return

the numeric position in a text string, you need to understand that

CHAPTER 3

Manipulating Strings

142

the position of characters in a text string begins with a value of 0,

the same as with indexed array elements. For example, the strpos()

function performs a case-sensitive search and returns the position of

the first occurrence of a substring within a string. You pass two argu-

ments to the strpos() function: The first argument is the string you

want to search, and the second argument contains the substring for

which you want to search. If the search substring is not found, the

strpos() function returns a Boolean value of FALSE. The following

code uses the strpos() function to determine whether the $Email

variable contains an @ character. Because the position of text strings

begins with 0, the echo statement returns a value of 9, even though

the @ character is the 10th character in the string.

$Email = "president@whitehouse.gov";

echo strpos($Email, '@'); // returns 9

If you simply want to determine whether a character exists in a string,

you need to keep in mind that PHP converts the Boolean values TRUE

and FALSE to 1 and 0, respectively. However, these values are char-

acter positions within a string. For example, the following statement

returns a value of 0 because “p” is the first character in the string:

$Email = "president@whitehouse.gov";

echo strpos($Email, 'p'); // returns 0

To determine whether the strpos() function (and other string func-

tions) actually returns a Boolean FALSE value and not a 0 representing

the first character in a string, you must use the strict equal operator

(===) or the strict not equal operator (!==). The following example

uses the strpos() function and the strict not equal operator to deter-

mine whether the $Email variable contains an @ character:

You first

encountered

the strict not

equal

operator in

Chapter 1.

$Email = "president@whitehouse.gov";

if (strpos($Email, '@') !== FALSE)

echo "<p>The e-mail address contains an @ character.</p>";

else

echo "<p>The e-mail address does not contain an @

character.</p>";

Because

the e-mail

address in

the $Email

variable in this

example only contains a

single period, you can

use either the strchr()

or strrchr() function.

To return the last portion of a string, starting with a specified char-

acter, you use strchr() or strrchr(). You pass to both functions

the string and the character for which you want to search. Both

functions return a substring from the specified characters to the end

of the string. The only difference between the two functions is that

the strchr() function starts searching at the beginning of a string,

whereas the strrchr() function starts searching at the end of a

string. The following code uses the strrchr() function to return the

top-level domain (TLD) of the e-mail address in the $Email variable:

$Email = "president@whitehouse.gov";

echo "<p>The top-level domain of the e-mail address is "

. strrchr($Email, ".") . ".</p>";


Working with Multiple Strings

To use the strpos() function to check whether e-mail addresses con-

tain ampersands and a period to separate the domain name from the

top-level domain:

1.

2.

Create a new document in your text editor.

Type the <!DOCTYPE> declaration, <html> element, document

head, and <body> element. Use the strict DTD and “E-Mail

Validator” as the content of the <title> element.

Add the following script section to the document body:

<?php

?>

143

3.

4.

Declare an array called $EmailAddresses. Populate the list

with several valid and invalid e-mail addresses. The following

code provides a good starting point, but you may add more

addresses.

$EmailAddresses = array(

"john.smith@php.test",

"mary.smith.mail.php.example",

"john.jones@php.invalid",

"alan.smithee@test",

"jsmith456@example.com",

"jsmith456@test",

"mjones@example",

"mjones@example.net",

"jane.a.doe@example.org");

The three top-level domains .test, .example, and .invalid,

as well as the three domains example.com, example.net, and

example.org, are special names that will never connect to a

real server.

5.

Add the following function to the beginning of the script

section, immediately after the declaration statement for the

$EmailAddresses array. The function uses two strpos()

functions to determine whether the string passed to it con-

tains an ampersand and a period. If the string contains both

characters, a value of TRUE is returned. If not, a value of FALSE

is returned.

function validateAddress($Address) {

if (strpos($Address, '@') !== FALSE &&

strpos($Address,

'.') !== FALSE)

return TRUE;

else

return FALSE;

}


CHAPTER 3

Manipulating Strings

6.

Add the following foreach statement immediately after

the validateAddress function declaration. The if con-

ditional expression passes the $Address variable to the

validateAddress() function. If the function returns a value

of FALSE, the echo statement executes.

foreach ($EmailAddresses as $Address) {

if (validateAddress($Address) == FALSE)

echo "<p>The e-mail address <em>$Address</em>

does not appear to be valid.</p>\n";

}

144

7.

Save the file as PHPEmail.php, 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 output for the preceding addresses is

shown in Figure 3-12.

Figure 3-12

Output of the E-Mail Validator script

8.

Close your Web browser window.

Replacing Characters and Substrings

In addition to finding and extracting characters in a string, you might

need to replace them. PHP provides a number of functions to replace

text within a string, including str_replace(), str_ireplace(), and

substr_replace().

The str_replace() and str_ireplace() functions both accept three

arguments: the string you want to search for, a replacement string,

and the string in which you want to replace characters. The replace-

ment functions do not modify the contents of an existing string.

Instead, they return a new string, which you can assign to a variable,

use in an echo statement, or use in your script in some other way. The


Working with Multiple Strings

following example demonstrates how to use the str_replace() func-

tion to replace “president” in the $Email variable with “vice.president”.

$Email = "president@whitehouse.gov";

$NewEmail = str_replace("president", "vice.president",

$Email);

echo $NewEmail;

// displays 'vice.president@whitehouse.gov'

145

Instead of replacing all occurrences of characters within a string, the

substr_replace() function allows you to replace characters within

a specified portion of a string. You pass to the substr_replace()

function the string you want to search, the replacement text, and the

starting and ending positions of the characters you want to replace.

If you do not include the last argument, the substr_replace() func-

tion replaces all the characters from the starting position to the end

of the string. For example, the following code uses the strpos() and

substr_replace() functions to replace “president” in the $Email

variable with “vice.president.”

$Email = "president@whitehouse.gov";

$NameEnd = strpos($Email, "@");

$NewEmail = substr_replace($Email, "vice.president", 0,

$NameEnd);

echo $NewEmail;

// displays 'vice.president@whitehouse.gov'

The following code demonstrates how to use the substr_replace()

function to replace text from one string when storing the value in a

new variable. The code uses the strpos() and strrpos() functions

to locate the starting and ending positions of the word “Medical” in

“American Medical Association”. The

substr_replace() function

then replaces the word “Medical” with the word “Heart”, changing the

name to “American Heart Association” when storing the value in the

new location. Figure 3-13 shows the results.

$FirstStudyPublisher = "American Medical Association";

$MiddleTermStart = strpos($FirstStudyPublisher, " ") + 1;

$MiddleTermEnd = strrpos($FirstStudyPublisher, " ") -

$MiddleTermStart;

$SecondStudyPublisher = substr_

replace($FirstStudyPublisher, "Heart",

$MiddleTermStart, $MiddleTermEnd);

echo "<p>The first study was published by the

$FirstStudyPublisher.</p>\n";

echo "<p> The second study was published by the

$SecondStudyPublisher.</p>\n";


CHAPTER 3

Manipulating Strings

146

Figure 3-13

Output of the Study Publisher script

To use the str_replace() function to display a list of American pres-

idents and their terms in office:

1.

2.

Create a new document in your text editor.

Type the <!DOCTYPE> declaration, <html> element, document

head, and <body> element. Use the strict DTD and “Presiden-

tial Terms” as the content of the <title> element.

Add the following script section to the document body:

<?php

?>

3.

4.

Declare an array called $Presidents. Populate the list with

the names of the first five presidents, as follows:

$Presidents = array(

"George Washington",

"John Adams",

"Thomas Jefferson",

"James Madison",

"James Monroe");

5.

Declare an array called $YearsInOffice. Populate the list

with the terms of the first five presidents, as follows:

$YearsInOffice = array(

"1789 to 1797",

"1797 to 1801",

"1801 to 1809",

"1809 to 1817",

"1817 to 1825");

6.

Declare a template string for the output as follows:

$OutputTemplate = "<p>President [NAME] served from

[TERM]</p>\n";


Working with Multiple Strings

7.

Add the following foreach loop to retrieve each president

and create an output string from the template string:

foreach ($Presidents as $Sequence => $Name) {

$TempString = str_replace("[NAME]", $Name,

$OutputTemplate);

$OutputString = str_replace("[TERM]",

$YearsInOffice[$Sequence],

$TempString);

echo $OutputString;

}

147

8.

Save the file as Presidents.php, 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/

Presidents.php. Figure 3-14 shows the output.

Figure 3-14

9.

Output of the Presidents.php script

Close your Web browser window.

Dividing Strings into Smaller Pieces

If you receive a text string that contains multiple data elements sepa-

rated by a common delimiter, you will probably want to split the

string into its individual elements. A delimiter is a character or string

that is used to separate components in a list. The delimiter is usu-

ally not found in any of the elements. For example, you may receive

a list of names, separated by commas. Although you could use some

of the string functions you’ve seen so far to manually parse such a

string into smaller pieces, you can save yourself a lot of work by using

the strtok() function to break a string into smaller strings, called

tokens. When it is first called, the syntax for the strtok() function


CHAPTER 3

Manipulating Strings

148

If you spec-

ify an empty

string as the

second argu-

ment of the

strtok() function, or if

the string does not con-

tain any of the separators

you specify, the

strtok() function

returns the entire string.

is $variable = strtok(string, separators);. The strtok()

function assigns to $variable the token (substring) from the begin-

ning of the string to the first separator. To assign the next token to

$variable, you call the strtok() function again, but only pass to

it a single argument containing the separator. The PHP scripting

engine keeps track of the current token and assigns the next token

to $variable, starting at the first character after the separator, each

time the strtok() function is called and until the end of the string is

reached. If there are no characters between two separators, between

the start of the string and the first separator, or between the last sepa-

rator and the end of the string, strtok() returns an empty string.

The first statement in the following code assigns the names of the

first five American presidents to the $Presidents variable, sepa-

rated by semicolons. The first strtok() function assigns the first

token (George Washington) to the $President variable. The while

statement then displays the token and assigns the next token to the

$President variable. The while loop iterates through the tokens until

the $President variable is equal to NULL. Figure 3-15 shows the

output.

$Presidents = "George Washington;John Adams;Thomas

Jefferson;James Madison;James Monroe";

$President = strtok($Presidents, ";");

while ($President != NULL) {

echo "$President<br />";

$President = strtok(";");

}

Figure 3-15

Using strtok() to divide a list using semicolons


Working with Multiple Strings

The strtok() function does not divide a string into tokens by using

a substring that is passed as its second argument. Instead, it divides

a string into tokens using any of the characters that are passed in

the second argument. For example, if you include a semicolon and

a space (“; ”) in the second argument for the strtok() function, the

string is split into tokens at each semicolon or space in the string. The

following example contains a modified version of the preceding code.

In this version, the separators arguments passed to the strtok()

functions contain a semicolon and a space. For this reason, the string

is split into tokens at each semicolon and individual space in the

$Presidents variable, as shown in Figure 3-16.

$Presidents = "George Washington;John Adams;Thomas

Jefferson;James Madison;James Monroe";

$President = strtok($Presidents, "; ");

while ($President != NULL) {

echo "$President<br />";

$President = strtok("; ");

}

149

Figure 3-16 Using strtok() to divide a list using

semicolons and spaces

To look for empty fields in a UNIX password file record using the

strtok() function:

1.

2.

Create a new document in your text editor.

Type the <!DOCTYPE> declaration, <html> element, document

head, and <body> element. Use the strict DTD and “Password

Fields” as the content of the <title> element.


CHAPTER 3

Manipulating Strings

3.

Add the following script section to the document body:

<?php

?>

4.

150

5.

Declare and initialize a string called $Record, as follows:

$Record = "jdoe:8W4dS03a39Yk2:1463:24:John

Doe:/home/jdoe:/bin/bash";

Declare an array called $PasswordFields, as follows:

$PasswordFields = array(

"login name",

"optional encrypted password",

"numerical user ID",

"numerical group ID",

"user name or comment field",

"user home directory",

"optional user command interpreter");

6.

Enter the following code to tokenize the string and display a

message for each missing field:

$FieldIndex = 0;

$ExtraFields = 0;

$CurrField = strtok($Record, ":");

while ($CurrField != NULL) {

if ($FieldIndex < count($PasswordFields))

echo "<p>The

{$PasswordFields[$FieldIndex]} is

<em>$CurrField</em></p>\n";

else {

++$ExtraFields;

echo "<p>Extra field # $ExtraFields is

<em>$CurrField</em></p>\n";

}

$CurrField = strtok(":");

++$FieldIndex;

}

7.

Save the file as PasswordFields.php, 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/

PasswordFields.php. Figure 3-17 shows the output.


Working with Multiple Strings

151

Figure 3-17

8.

Using strtok() to parse a password record

Close your Web browser window.

Converting between Strings and Arrays

In addition to splitting a string into tokens, you can split a string into

an array, in which each array element contains a portion of the string.

In most cases, you will probably find it more useful to split a string

into an array instead of tokens because you have more control over

each array element. With strings that are split with the strtok()

function, you can only work with a substring if it is the current token.

Although tokenizing a string is useful if you want to quickly display or

iterate through the tokens in a string, you need to assign the tokens

to another variable or array if you want to modify the tokens in any

way. By contrast, when you split a string into an array, portions of the

string are automatically assigned to elements.

You use the str_split() or explode() function to split a string

into an indexed array. The str_split() function splits each

character in a string into an array element, using the syntax

$array = str_split(string[, length]);. The length argument

represents the number of characters you want assigned to each array

element. The explode() function splits a string into an indexed array

at a specified separator. The syntax for the explode() function is

$array = explode(separator, string);. Be sure to notice that the

order of the arguments for the explode() function is the reverse of

CHAPTER 3

Manipulating Strings

the arguments for the strtok() function. The following code dem-

onstrates how to split the $Presidents string into an array named

$PresidentArray:

$Presidents = "George Washington;John Adams;Thomas

Jefferson;James Madison;James Monroe";

$PresidentArray = explode(";", $Presidents);

foreach ($PresidentArray as $President) {

echo "$President<br />";

}

152

If you pass

to the

explode()

function an

empty string

as the separator argu-

ment, the function returns

a Boolean value of

FALSE.

If the string does not contain the specified separator, the entire string

is assigned to the first element of the array. Also, unlike the strtok()

function, the explode() function does not separate a string at any

character that is included in the separator argument. Instead, the

explode() function evaluates the characters in the separator argu-

ment as a substring. For example, a semicolon and a space separate

each president’s name in the following code. Therefore, you pass “; ”

as the separator argument of the explode() function.

$Presidents = "George Washington; John Adams; Thomas

Jefferson; James Madison; James Monroe";

$PresidentArray = explode("; ", $Presidents);

foreach ($PresidentArray as $President) {

echo "$President<br />";

}

The opposite of the explode() function is the implode() function,

which combines an array’s elements into a single string, separated

by specified characters. The syntax for the implode() function

is $variable = implode(separator, array);. The following

example first creates an array named $PresidentsArray, then uses

the implode() function to combine the array elements into the

$Presidents variable, separated by a comma and a space. Figure 3-18

shows the output.

$PresidentsArray = array("George Washington", "John

Adams", "Thomas Jefferson", "James Madison", "James

Monroe");

$Presidents = implode(", ", $PresidentsArray);

echo $Presidents;

Figure 3-18

Using implode() to build a string from an array


Working with Multiple Strings

To modify PasswordFields.php so the record is split into an array

instead of tokens:

1.

2.

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

Replace the declaration and initialization of $CurrField with

the following statement:

$Fields = explode(":",$Record);

153

3.

Replace the while loop with a foreach loop as follows:

foreach ($Fields as $FieldIndex => $FieldValue) {

if ($FieldIndex < count($PasswordFields))

echo "<p>The

{$PasswordFields[$FieldIndex]} is

<em>$FieldValue</em></p>\n";

else {

++$ExtraFields;

echo "<p>Extra field # $ExtraFields is

<em>$FieldValue</em></p>\n";

}

}

4.

Save the PasswordFields.php file, upload it to the server, and

then open the file in your Web browser by entering the fol-

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

Chapter/ PasswordFields.php. The output should still look like

Figure 3-17.

Close your Web browser window.

5.

Short Quiz

1.

What function can be used to determine if a specific charac-

ter exists in a string?

What is the difference between the str_replace() function

and the str_ireplace() function?

What functions are used to split a string into an indexed

array?

2.

3.


CHAPTER 3

Manipulating Strings

Comparing Strings

In Chapter 1, you studied various operators that you can use with

PHP, including comparison operators. Although comparison opera-

tors are most often used with numbers, they can also be used with

strings. The following statement uses the comparison operator (==)

to compare two variables containing text strings:

$Florida = "Miami is in Florida.";

$Cuba = "Havana is in Cuba.";

if ($Florida == $Cuba)

echo "<p>Same location.</p>";

else

echo "<p>Different location.</p>";

154

Because the text strings are not the same, the else clause displays

the text “Different location.” You can also use comparison operators

to determine whether one letter occurs later in the alphabet than

another letter. In the following code, the first echo statement executes

because the letter “B” occurs later in the alphabet than the letter “A”:

$FirstLetter = "A";

$SecondLetter = "B";

if ($SecondLetter > $FirstLetter)

echo "<p>The second letter occurs later in the alphabet

than the first letter.</p>";

else

echo "<p>The second letter occurs earlier in the alphabet

than the first letter.</p>";

You use the

ord() func-

tion to

return the

ASCII value

of a character, and the

chr() function to return

the character for an

ASCII value.

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