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

When working with strings, you often cannot guarantee that they

will be in the correct case. This is especially true when dealing with

strings from external sources, such as database queries or user form

Input. Php provides several functions for manipulating the case of a

string.

For many types of codes, whether within the computer world or

not, text strings are expected to appear only in uppercase letters.

For example, U.S. state and Canadian province postal abbreviations

should always be uppercase. The strtoupper() function converts

all of the letters in a string to uppercase. Similarly, the strtolower()

function converts all of the letters in a string to lowercase. For


CHAPTER 3

The

ucfirst()

and

lcfirst()

functions

only change the first char-

acter of a string. The

ucwords() function

only changes the first

character of each word.

These functions do not

change the case of any

other character in a

string. To ensure that the

remaining characters in a

string are lowercase

when using the

ucfirst() and

ucwords()functions,

you need to use the

strtolower() function

on the string first. To

ensure that the remaining

characters are uppercase

when using the

lcfirst() function,

you need to use the

strtoupper() function

on the string first.

Manipulating Strings

example, this function is useful when converting a document from

HTML to XHTML, because the XHTML standard specifies that all

element and attribute tags must be lowercase.

When working with natural languages, more complex conversions

are needed. Sentences in English start with an uppercase letter.

The ucfirst() function ensures that the first character of a string

Is uppercase. If you need the reverse of ucfirst(), the lcfirst()

function converts the first character of a string to lowercase. Titles of

books, songs, poems, and articles usually have the first letter of each

word capitalized. The ucwords() function converts the first character

of each word in a string to uppercase.

Consider the following example and the output shown in Figure 3-8:

$ConfusingText = "tHIs seNTEnCE iS HArD to rEAD.";

echo "<h1>Confusing Text</h1>\n";

echo "ucfirst: " . ucfirst($ConfusingText) . "<br />\n";

echo "lcfirst: " . lcfirst($ConfusingText) . "<br />\n";

echo "ucwords: " . ucwords($ConfusingText) . "<br />\n";

$LowercaseText = strtolower($ConfusingText);

echo "<h1>Lowercase Text</h1>\n";

echo "ucfirst: " . ucfirst($LowercaseText) . "<br />\n";

echo "lcfirst: " . lcfirst($LowercaseText) . "<br />\n";

echo "ucwords: " . ucwords($LowercaseText) . "<br />\n";

136

Figure 3-8 Using the ucfirst(), lcfirst(),

and ucwords() functions


Working with a Single String

In the three lines under the “Confusing Text” title, it is still very dif-

ficult to read the text, because the strings are a mix of uppercase and

lowercase letters. In addition, it is hard to see what changed in the

three lines. The three lines under the “Lowercase Text” title are much

clearer to read and it is easier to see what changed, because all of the

text started in lowercase.

To manipulate the case of a string:

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

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

Add the following script section to the document body:

<?php

?>

3.

4.

Declare and initialize a string called $StartingText, as

follows:

$StartingText = "mAdAm, i'M aDaM.";

5.

Add the following four lines of code to convert and display

the string in uppercase and lowercase:

$UppercaseText = strtoupper($StartingText);

$LowercaseText = strtolower($StartingText);

echo "<p>$UppercaseText</p>\n";

echo "<p>$LowercaseText</p>\n";

The

ucfirst()

and

ucwords()

functions do

not always capitalize a

proper name correctly,

such as in strings that

require more than one

capital letter. Consider

trying to convert the

strings “des moines”,

“mary-elizabeth”, and

“dimaggio” to the proper

names “Des Moines”,

“Mary-Elizabeth”, and

“DiMaggio”. The

ucfirst() function will

convert the strings to

“Des moines”, “Mary-

elizabeth”, and

“Dimaggio”, respectively.

The ucwords() function

will properly convert “des

moines” to “Des Moines”,

but its conversions of the

other two strings will

match those of the

ucfirst() function.

137

6.

Add the following four lines to display the text with different

mixes of uppercase and lowercase letters:

echo "<p>" . ucfirst($LowercaseText) . "</p>\n";

echo "<p>" . lcfirst($UppercaseText) . "</p>\n";

$WorkingText = ucwords($LowercaseText);

echo "<p>$WorkingText</p>\n";

7.

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

WordPlay.php. Figure 3-9 shows the output in your Web

browser window.


CHAPTER 3

Manipulating Strings

138

Figure 3-9

Output of WordPlay.php

8.

Close your Web browser window.

Encoding and Decoding a String

Because of the close relationship between XHTML, the Internet, and

PHP, several functions are built into PHP for dealing with Web pages.

The htmlspecialchars() and htmlspecialchars_decode() func-

tions in XHTML are only useful for processing strings. XHTML has

five reserved characters: the ampersand (&), double quotation mark

("), single quotation mark ('), left angle bracket or “less than” symbol

(<), and right angle bracket or “greater than” symbol (>). To display

these characters as text on an XHTML page, they should be encoded

using HTML character entities. The htmlspecialchars() function

converts any occurrence of these five characters to their equivalent

HTML character entity. Specifically, ‘&’ becomes ‘&’, ‘"’ becomes

‘"’, ‘'’ becomes ‘'’, ‘<’ becomes ‘<’, and ‘>’ becomes

‘>’. The htmlspecialchars_decode() function performs the

reverse operation, converting the HTML character entities into their

equivalent characters.

Passwords are required for secure access to a Web site. Storing pass-

words as plain text strings creates security and privacy issues. The

md5() function is a way to avoid storing passwords as plain text.

The md5() function uses a strong encryption algorithm (called the

Message-Digest Algorithm) to create a one-way hash of the entered

string. A one-way hash is a fixed-length string based on the entered

text, from which it is nearly impossible to determine the original text.

Because it is a one-way hash, there is no equivalent decode function

for the md5() function. In theory, a one-way hash makes it impossible

Turning on

the PHP

configuration

setting

“ENT_

NOQUOTES” disables the

conversion of the double

quotation mark. Turning

on the PHP configuration

setting “ENT_QUOTES”

enables the conversion of

the single quotation

mark.


Working with a Single String

to convert the stored hash value back to the original password to

compare against an entered password. Instead, the entered pass-

word is passed to the md5() function, and the resulting hash value is

compared against the stored hash value. If the two are the same, the

entered password is considered to be valid.

PHP

provides a

number of

functions for

encrypting

strings using different

algorithms.

Although

converting a

one-way hash

value back to

the original

value is supposedly

impossible, hackers have

managed to “crack” many

one-way hash algorithms,

including the md5() algo-

rithm. Encryption algo-

rithms, like physical

locks, will not stop some-

one who is determined to

defeat them.

139

Other Ways to Manipulate a String

If a string has leading or trailing spaces, the trim() function will

remove them. To remove only the leading spaces, use the ltrim()

(left trim) function. To remove only the trailing spaces, use the

rtrim() (right trim) function.

To return only a portion of a string, use the substr() function.

This function takes the input string as the first parameter, the start-

ing position as the second parameter, and the length of the string to

return as an optional third parameter. For numbers that are zero or

positive, the starting position is calculated from the start of the string,

with zero being the first character. For negative numbers, the starting

position is calculated from the end of the string, with –1 being the

last character. If the length is omitted or is greater than the remain-

ing length of the string, the entire remainder of the string is returned.

Figure 3-10 shows the output of the following example:

$ExampleString = "woodworking project";

echo substr($ExampleString,4) . "<br />\n";

echo substr($ExampleString,4,7) . "<br />\n";

echo substr($ExampleString,0,8) . "<br />\n";

echo substr($ExampleString,-7) . "<br />\n";

echo substr($ExampleString,-12,4) . "<br />\n";

Figure 3-10

Some examples using the substr() function


CHAPTER 3

Manipulating Strings

Many more functions are available in PHP to manipulate the charac-

ters in a string. Although they will not all be discussed in this section,

two deserve special mention. The strrev() function reverses the

order of the characters in a string, and the str_shuffle() function

randomly scrambles the order.

140

To add the md5(), substr(), strrev(), and str_shuffle() functions

to the Word Play example:

1.

2.

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

Add the following five lines before the end of the PHP block:

echo

echo

echo

echo

echo

"<p>"

"<p>"

"<p>"

"<p>"

"<p>"

.

.

.

.

.

md5($WorkingText) . "</p>\n";

substr($WorkingText,0,6) . "</p>\n";

substr($WorkingText,7) . "</p>\n";

strrev($WorkingText) . "</p>\n";

str_shuffle($WorkingText) . "</p>\n";

3.

Save the WordPlay.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/

WordPlay.php. Figure 3-11 shows the new Web page.

Figure 3-11

Output of the Word Play script

4.

Close your Web browser window.

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