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

Xhtml source code gen-

erated by the PHP script.

Although this normally

has no effect on the Web

browser display, it makes

the XHTML source code

easier to read and debug.

The print statement

automatically appends a

“new line” character to

the string it returns.

The following code shows another example of an escape character,

this time with the double quotation escape sequence (\"). Figure 3-4

shows the output.

$Speaker = "Julius Caesar";

echo "<p>\"Et tu, Brute!\" exclaimed $Speaker.</p>";

Figure 3-4

Using escape sequences for double quotes


CHAPTER 3

Manipulating Strings

130

Because the string in the previous example contained a variable, the

string would not display as intended if you used single quotes around

it, as discussed previously. Remember from Chapter 1 that vari-

ables are not expanded when the string is enclosed in single quotes.

Similarly, the escape sequences listed in Table 3-1 will be treated as

literal text if the string is enclosed in single quotes.

An alternative to using the double quotation mark escape sequence

is to use single quotation marks for the starting text portion of the

literal string and then combine the $Speaker variable with the con-

catenation operator, as follows:

$Speaker = "Julius Caesar";

echo '<p>"Et tu, Brute!" exclaimed '

. $Speaker . ".</p>";

To use escape sequences to format text:

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 “Format-

ted Text” as the content of the <title> element.

Add the following script section to the document body:

<?php

?>

3.

4.

Declare and initialize a variable called $DisplayValue, as

follows:

$DisplayValue=9.876;

5.

Add the following PHP code to display some unformatted

text. Be sure to include the code for the opening and clos-

ing XHTML <pre> tags. Normally, the Web browser will treat

all new lines, carriage returns, and tabs as spaces. Using the

<pre> tag tells the Web browser not to convert those charac-

ters to spaces.

echo

echo

echo

echo

echo

"<pre>\n";

"Unformatted text line 1. ";

"Unformatted text line 2. ";

"$DisplayValue = $DisplayValue";

"</pre>\n";

6.

Add the following PHP code to display some formatted text:

echo

echo

echo

echo

echo

"<pre>\n";

"Formatted text line 1. \r\n";

"\tFormatted text line 2. \r\n";

"\$DisplayValue = $DisplayValue";

"</pre>\n";


Constructing Text Strings

7.

Save the file as FormattedText.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/

FormattedText.php. Figure 3-5 shows the output. Notice

that the unformatted lines run together but the formatted

lines do not. The second formatted line is indented, and the

value of $DisplayValue (9.876) appears at the beginning of

the third line of the unformatted section. However, the text

“$DisplayValue” appears at the beginning of the third line of

the formatted section.

131

Figure 3-5

8.

Output of FormattedText.php

Close your Web browser window.

Simple and Complex String Syntax

Values and variables can be combined in a literal string using simple

or complex syntax. Simple string syntax allows you to use the value

of a variable within a string by including the variable name inside a

text string enclosed by double quotation marks (not single quotation

marks). For example, the following code displays the text “Do you

have any broccoli?” in the Web browser:

$Vegetable = "broccoli";

echo "<p>Do you have any $Vegetable?</p>";

When the PHP scripting engine encounters a dollar sign within a

text string, it attempts to evaluate any characters that follow the dol-

lar sign as part of the variable name until it comes to a character that

is not allowed in an identifier, such as a space. With the preceding

example, the $Vegetable variable is interpreted correctly because the

question mark is not a legal character for an identifier. However, con-

sider the following version of the preceding code:

$Vegetable = "tomato";

echo "<p>Do you have any $Vegetables?</p>";


CHAPTER 3

Manipulating Strings

132

Because an ‘s’ is appended to the $Vegetable variable name, the pre-

ceding echo statement displays incorrectly. The PHP scripting engine

is attempting to locate a variable named $Vegetables (plural), which

has not been declared, so no text is displayed in place of the variable

name. To make the preceding code work, you need to surround the

variable name with curly braces ({}), as shown in the following exam-

ple. This type of structure, in which variables are placed within curly

braces inside a string, is called complex string syntax.

$Vegetable = "carrot";

echo "<p>Do you have any {$Vegetable}s?</p>";

The preceding echo statement displays the text string “Do you have

any carrots?” Complex string syntax is only recognized if the opening

brace is immediately before or after a variable’s dollar sign. The fol-

lowing version of the preceding code also displays correctly:

$Vegetable = "carrot";

echo "<p>Do you have any ${Vegetable}s?</p>";

However, if you place any characters between the opening brace and

the dollar sign, the contents of the string are interpreted as literal

values. For example, because the following code includes a space

between the opening brace and the dollar sign, the echo statement

displays the text string “Do you have any { carrot}s?”:

$Vegetable = "carrot";

echo "<p>Do you have any { $Vegetable}s?</p>";

To display a list of authors and their works:

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 “Books

and Authors” as the content of the <title> element.

Add the following script section to the document body:

<?php

?>

3.

4.

Declare and initialize an array called $Books, as follows:

$Books = array("The Adventures of Huckleberry Finn",

"Nineteen Eighty-Four",

"Alice's Adventures in Wonderland",

"The Cat in the Hat");

5.

Declare and initialize an array called $Authors, as follows:

$Authors = array("Mark Twain",

"George Orwell",

"Lewis Carroll",

"Dr. Seuss");


Constructing Text Strings

6.

Declare and initialize an array called $RealNames, as follows:

$RealNames = array("Samuel Clemens",

"Eric Blair",

"Charles Dodson",

"Theodor Geisel");

7.

Create a for loop to display a string that combines the values

from the three arrays, as follows. Note the use of complex

string syntax to ensure that the PHP scripting engine handles

the array elements correctly.

for ($i = 0; $i < count($Books); ++$i)

echo "<p>The real name of {$Authors[$i]}, ".

"the author of \"{$Books[$i]}\", ".

"is {$RealNames[$i]}.</p>";

133

8.

Save the file as BooksAndAuthors.php, upload it to the

server, and then open the file in your Web browser by enter-

ing the following URL:

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

BooksAndAuthors.php. Figure 3-6 shows the output in your

Web browser window.

Figure 3-6

9.

Output of the Books and Authors script

Close your Web browser window.

Short Quiz

1.

Explain the difference between a concatenation operator and

a concatenation assignment operator.

Describe two ways to display double quotation marks within a

literal string.

Describe the use of curly braces in complex string syntax.

2.

3.


CHAPTER 3

Manipulating Strings

Working with a Single String

PHP provides a large number of functions for analyzing, altering, and

parsing text strings. In this section, you will study basic techniques

for manipulating an individual string, including how to count char-

acters and words. You will also learn how to transpose, convert, and

change the case of text within a string.

134

Counting Characters and Words in a String

You will often find it necessary to count characters and words in

strings. For example, you might need to count characters in a pass-

word to ensure that a user selects a password with a minimum num-

ber of characters. Or, you might have a Web page that allows users

to submit classified ads that cannot exceed a maximum number of

words.

The most commonly used string-counting function is the strlen()

function, which returns the total number of characters in a string.

You pass to the strlen() function a literal string or the name of a

string variable whose characters you want to count. For example, the

following code uses the strlen() function to count the number of

characters in a variable named $BookTitle. The echo statement dis-

plays “The book title contains 23 characters.”

$BookTitle = "The Cask of Amontillado";

echo "<p>The book title contains " . strlen($BookTitle)

. " characters.</p>";

The

strlen()

function

counts

escape

sequences such as \n as

one character.

Another commonly used string-counting function is the

str_word_count() function, which returns the number of words in a

string. You pass to the str_word_count() function a literal string or

the name of a string variable whose words you want to count. The

following example shows a modified version of the preceding code,

but this time with the str_word_count() function. The echo statement

displays “The book title contains 4 words.”

$BookTitle = "The Cask of Amontillado";

echo "<p>The book title contains " .

str_word_count($BookTitle)

. " words.</p>";

To show the length and word count of some book titles:

1.

Return to the BooksAndAuthors.php script in your text

editor.

Change the content of the <title> element to “Title

Information.”

2.


Working with a Single String

3.

4.

Delete the $Authors and $RealNames arrays.

Modify the for loop to display the information about the

book titles, as follows:

for ($i = 0; $i < count($Books); ++$i)

echo "<p>The title \"{$Books[$i]}\" contains " .

strlen($Books[$i]) . " characters and " .

str_word_count($Books[$i]) . " words.</p>";

135

5.

Save the file as TitleInfo.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/

TitleInfo.php. Figure 3-7 shows the output in your Web

browser window.

Figure 3-7

6.

Output of the Title Information script

The

count_

chars()

function

returns an

array of the 256 ASCII

codes, where the value of

each element is the

number of times that

element occurs in the

parameter string.

Close your Web browser window.

Modifying the Case of a String

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