Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 86 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
86
Dung lượng
1,86 MB
Nội dung
throughout a user's visit from page to page of the website. Finally, we'd use the information to generate a "check out" page to verify the order. When the customer is ready to order, we can add their name, address and possibly credit card information to the user's table and generate the order. In this scenario we would probably have to generate a random, temporary userid and would most probably use the TableDrop() method after the order is generated to free up system resources. It is extremely useful to use the require() function to incorporate your class descriptions and commonly used instance declarations in your scripts. As stated before, the ability to use your classes in many different scripts is one of the key reasons for creating them. Summary Object-oriented programming allows programmers to refer to related variables and functions as a single entity called an object or instance. It incorporates three basic principles: ❑ abstraction ❑ encapsulation ❑ inheritance A class is a template that defines the variables and functions of an object. Class variables are referred to as properties. Class functions are referred to as methods. Class methods and properties are referenced using the -> operator. Creating an instance is called instantiation and is accomplished using the new statement. Constructors are special methods that are executed whenever an instance is created. Constructors are created by giving the method the same name as the class. A class may inherit properties and methods from a previously declared class by using the extends argument with the new statement. This newly created class is known as the child class. The original class is known as the parent class. TEAM FLY PRESENTS Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 10 String Manipulation and Regular Expressions In many applications you will need to do some kind of manipulation or parsing of strings. Whether you are attempting to validate user data or extract data from text files, you need to know how to handle strings. In this chapter we will take a look at some of PHP's string functions, and then explore and employ regular expressions. Basic String Functions PHP includes dozens of functions for handling and processing strings. Some of the most common ones are described below. A full listing can be found in Appendix A. substr() string substr (string source, int begin, int [length]); The substr() function returns a part of a string. It receives three arguments (two required and one optional). The first argument is the source string to be parsed. The second argument is the position at which to begin the return string, where the first character's position is counted as zero. Therefore: echo (substr("Christopher", 1)); will print hristopher. If the second argument is negative, substr() will count backwards from the end of the source string: echo (substr("Christopher", -2)); TEAM FLY PRESENTS Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com will print er. This basically says "Return the piece of the string beginning at the second-to-last character". The third argument is optional. It is an integer that specifies the length of the substring to be returned. echo (substr("Christopher", -5, 3)); // Prints 'oph' The code above returns a 3-character string beginning with the fifth-from-last character of the source string. If a negative length is specified, the returned string will end that many characters from the end of the source. Here are a few more examples: // The string beginning at the 3rd-from-last echo (substr("Christopher", -3)); // Prints 'her' // The 3rd, 4th, and 5th chars echo (substr("Christopher", 2, 3)); // Prints 'ris' // From 3rd char to 3rd-from-last echo (substr("Christopher", 2, -3)); // Prints 'ristop' // From 6th-from-last to 3rd-from-last echo (substr("Christopher", -6, -3)); // Prints 'top' // A negative string! echo (substr("Christopher", 7, -8)); // Prints '' trim() Useful for "cleaning up" user input, trim() simply strips the whitespace characters (spaces, tabs, newlines) from the beginning and end of a string and returns the "trimmed" string: echo (trim(" sample string ")); // prints 'sample string' If you wish to only trim the beginning of the string, use ltrim() (left trim). To trim only the end of a string, use chop(). chr() chr() receives an integer that represents an ASCII code, and returns the corresponding character. echo (chr(34)); // Prints a quotation mark " This is equivalent to: TEAM FLY PRESENTS Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com echo ("\""); // Prints a quotation mark ord() ord() is chr()'s complement. It receives a character and returns the corresponding ASCII code as an integer. if ($c != ord(9) && $c != ord(13)) { // Only append $c if not tab or enter $my_string .= $c; } strlen() strlen() returns the number of characters in a string. echo (strlen ("Christopher")); // Prints 11 Among other uses, strlen() can come in handy when enforcing field size restrictions: if (strlen($userinput) > 30) { echo ("Please limit input to 30 characters."); } printf() and sprintf() The functions printf() and sprintf() each produce a string formatted according to your instructions. printf() prints the formatted string to the browser without returning any value; whereas sprintf() returns the formatted string without printing it to the browser, so that you can store it in a variable or database. The synopsis looks like this: string sprintf(string format, mixed [args] ); The format string indicates how each of the arguments should be formatted. For example, the format string “%d” in the example below renders the string “20 dollars” as the decimal value “20”: $dollars = "20 dollars"; printf ("%d", $dollars); // Prints: 20 The format string performs its task through directives. Directives consist of ordinary characters that appear unchanged in the output string, as well as conversion specifications, which we will examine in a moment. This example prints "20" as "20.00": $dollars = 20; printf ("%.2f", $dollars); The format string is %.2f, and the argument is $dollars. The %.2f makes up the conversion specification. TEAM FLY PRESENTS Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com A conversion specification begins with a % and consists of up to five specifiers (most of which are optional). They are (from left-to-right): 1. An optional padding specifier. This is a component that indicates what character should be used to fill out the result string to the desired size. By default, the padding specifier is a space. With numbers, it is common to use zeroes as a padding specifier. To do so, just type a zero as the padding specifier in the format string. If you want a padding specifier other than space or zero, place a single quote before the character in the format string. For example, to fill out a string with periods, type '. as the padding specifier component in the format string. 2. An optional alignment specifier. To make the string left-justified, include a hyphen (-) as the alignment specifier. By default, strings are right-justified. 3. An optional minimum width specifier. This is simply an integer that indicates the minimum number of characters the string should be. If you specify a width of 6, and the source string is only three characters wide, the rest of the string will be padded with the character indicated by the padding specifier. Note that for floating point numbers, the minimum width specifier determines the number of characters to the left of the decimal point. 4. An optional precision specifier. For floating point numbers (i.e. doubles), this number indicates how many digits to display after the decimal point. For strings, it indicates the maximum length of the string. In either case, the precision specifier appears after a decimal point. For all other data types (other than double or string) the precision specifier does nothing. 5. A required type specifier. The type specifier indicates the type of data being represented. It can be one of the following values: d - Decimal integer. b - Binary integer. o - Octal integer. x - Hexadecimal integer (with lowercase letters). X - Hexadecimal integer (with uppercase letters). c - Character whose ASCII code is integer value of the argument. f - Double (Floating-point number). e - Double, using exponential notation. s - String. % - A literal percent sign. This does not require a matching argument. Unlike other languages, PHP does not use E, g, G or u type specifiers. In our example above, %.2f uses the default values of the padding, alignment, and minimum width specifiers. It explicitly specifies that the value should be represented as a double (f) with two digits after the decimal point (.2). As mentioned above, it is also possible to include ordinary characters in the format string that are to be printed literally. Instead of “20.00”, suppose we would like to print “$20.00”. We can do so simply by adding a “$” before the argument: TEAM FLY PRESENTS Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com $dollars = 20; printf ("$%.2f", $dollars); // prints: $20.00 Let’s examine a more complex example: In a table of contents, one usually lists the name of a chapter on the left, and a page number on the right. Often, the rest of the line in between is filled with dots to help the eye navigate the space between the left and right columns. This can be achieved by left-justifying the chapter name and using a period as a padding specifier. In this case, our printf() statement will have three arguments after the format string: one for the chapter name, one for the page number, and one for the newline tag. Note that in a browser a monospace font is needed to ensure proper alignment, since we are using printf() instead of a table. // Set variables: $ch3_title = "Bicycle Safety"; $ch3_pg = 83; $ch4_title = "Repairs and Maintenance"; $ch4_pg = 115; // Print the TOC printf ("%' 40.40s%'.3d%s", $ch3_title, $ch3_pg, "<BR>\n"); printf ("%' 40.40s%'.3d%s", $ch4_title, $ch4_pg, "<BR>\n"); This code will print: Bicycle Safety 83 Repairs and Maintenance 115 Let us examine this format string (%' 40.40s%'.3d%s) closely. It consists of three directives. The first, %' 40.40s, corresponds to the chapter argument. The padding specifier is '., indicating that periods should be used. The hyphen specifies left-justification. The minimum and maximum sizes are set to forty (40.40), and the s clarifies that the value is to be treated as a string. The second directive, %'.3d, corresponds to the page number argument. It produces a right-justified, period-padded ('.) decimal integer d with a minimum width of three characters. The third directive, %s, simply treats <BR>\n as a string. number_format() The printf() and sprintf() functions can produce sophisticated formatted output of strings and numbers. If you only need simple formatting of numbers, you can use the mathematical function, number_format(): string number_format (float num, int precision, string dec_point, string thousands_sep); The function takes one, two, or four arguments. (Three arguments will result in an error.) If only the first argument is used, num is depicted as an integer with commas separating the thousands: $num = 123456789.1234567; TEAM FLY PRESENTS Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com echo (number_format ($num)); This prints: 123,456,789 If the first two arguments are used, the number will be shown with precision digits after the decimal point. The decimal point will be represented as a dot and commas will separate the thousands: $$num = 123456789.1234567; echo (number_format ($num, 4)); This prints: 123,456,789.1235 The third and fourth arguments allow you to change the characters representing the decimal point and thousands separator: $$num = 123456789.1234567; echo (number_format ($num, 7, chr(44), " ")); // Note: chr(44) == comma This prints: 123 456 789,1234567 Regular Expressions Regular expressions provide a means for advanced string matching and manipulation. They are very often not a pretty thing to look at. For instance: ^.+@.+\\ +$ This useful but scary bit of code is enough to give some programmers headaches and enough to make others decide that they don't want to know about regular expressions. But not you! Although they take a little time to learn, regular expressions, or REs as they're sometimes known, can be very handy; and once you have learned how to use them in PHP, you can apply the same knowledge (with slight modifications) to other languages and UNIX utilities that employ regular expressions, like Perl, JavaScript, sed, awk, emacs, vi, grep, etc. Basic Pattern Matching Let's start with the basics. A regular expression is essentially a pattern, a set of characters that describes the nature of the string being sought. The pattern can be as simple as a literal string; or it can be extremely complex, using special characters to represent ranges of characters, multiple occurrences, or specific contexts in which to search. Examine the following pattern: TEAM FLY PRESENTS Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com ^once This pattern includes the special character ^, which indicates that the pattern should only match for strings that begin with the string "once"; so the string "once upon a time" would match this pattern, but the string "There once was a man from Nantucket" would not. Just as the ^ character matches strings that begin with the pattern, the $ character is used to match strings that end with the given pattern. bucket$ would match the string "Who kept all of his cash in a bucket", but it would not match "buckets". ^ and $ can be used together to match exact strings (with no leading or trailing characters not in the pattern). For example: ^bucket$ matches only the string "bucket". If the pattern does not contain ^ or $, then the match will return true if the pattern is found anywhere in the source string. For the string: There once was a man from Nantucket Who kept all of his cash in a bucket the pattern once would result in a match The letters in the pattern ("o", "n", "c", and "e") are literal characters. Letters and numbers all match themselves literally in the source string. For slightly more complex characters, such as punctuation and whitespace characters, we use an escape sequence. Escape sequences all begin with a backslash (\). For a tab character, the sequence is \t. So if we want to detect whether a string begins with a tab, we use the pattern: ^\t This would match the strings: But his daughter, named Nan Ran away with a man since both of these lines begin with tabs. Similarly, \n represents a newline character, \f represents a form feed, and \r represents a carriage return. For most punctuation marks, you can simply escape them with a \. Therefore, a backslash itself would be represented as \\, a literal . would be represented as \., and so on. A full list of these escaped characters can be found in Appendix E. Character Classes In Internet applications, regular expressions are especially useful for validating user input. You want to make sure that when a user submits a form, his or her phone number, address, e-mail address, credit card number, etc. all make reasonable sense. Obviously, you could not do this by literally matching individual TEAM FLY PRESENTS Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com words. (To do that, you would have to test for all possible phone numbers, all possible credit card numbers, and so on.) We need a way to more loosely describe the values that we are trying to match, and character classes provide a way to do that. To create a character class that matches any one vowel, we place all vowels in square brackets: [AaEeIiOoUu] This will return true if the character being considered can be found in this "class", hence the name, character class. We can also use a hyphen to represent a range of characters: [a-z] // Match any lowercase letter [A-Z] // Match any uppercase letter [a-zA-Z] // Match any letter [0-9] // Match any digit [0-9\.\-] // Match any digit, dot, or minus sign [ \f\r\t\n] // Match any whitespace character Be aware that each of these classes is used to match one character. This is an important distinction. If you were attempting to match a string composed of one lowercase letter and one digit only, such as "a2", "t6", or "g7"; but not "ab2", "r2d2", or "b52", you could use the following pattern: ^[a-z][0-9]$ Even though [a-z] represents a range of twenty-six characters, the character class itself is used to match only the first character in the string being tested. (Remember that ^ tells PHP to look only at the beginning of the string. The next character class, [0-9] will attempt to match the second character of the string, and the $ matches the end of the string, thereby disallowing a third character. We’ve learned that the carat (^) matches the beginning of a string, but it can also have a second meaning. When used immediately inside the brackets of a character class, it means "not" or "exclude". This can be used to "forbid" characters. Suppose we wanted to relax the rule above. Instead of requiring only a lowercase letter and a digit, we wish to allow the first character to be any non-digit character: ^[^0-9][0-9]$ This will match strings such as "&5", "g7" and "-2"; but not "12" or "66". Here are afew more examples of patterns that exclude certain characters using ^: [^a-z] // Any character that is not a lowercase letter [^\\\/\^] // Any character except (\), (/), or (^) [^\"\'] // Any character except (") or (') The special character "." is used in regular expressions to represent any non-newline character. Therefore the pattern ^.5$ will match any two-character string that ends in five and begins with any character (other than newline). The pattern . by itself will match any string at all, unless it is empty or composed entirely of newline characters. Several common character classes are "built in" to PHP regular expressions. Some of them are listed below: TEAM FLY PRESENTS Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Character Class Description [[:alpha:]] Any letter [[:digit:]] Any digit [[:alnum:]] Any letter or digit [[:space:]] Any whitespace [[:upper:]] Any uppercase letter [[:lower:]] Any lowercase letter [[:punct:]] Any punctuation mark [[:xdigit:]] Any hexadecimal digit (equivalent to [0-9a-fA-F]) Detecting Multiple Occurrences Among other things, we now know how to match a letter or a digit. More often than not, though, one wants to match a word or a number. A word consists of one or more letters, and a number consists of one or more digits. Curly braces ({}) can be used to match multiple occurrences of the characters and character classes that immediately precede them. Character Class Description ^[a-zA-Z_]$ match any letter or underscore ^[[:alpha:]]{3}$ match any three-letter word ^a$ match: a ^a{4}$ match: aaaa ^a{2,4}$ match: aa, aaa, or aaaa ^a{1,3}$ match: a, aa, or aaa ^a{2,}$ match a string containing two or more a's ^a{2,} match aardvark and aaab, but not apple a{2,} match baad and aaa, but not Nantucket \t{2} match two tabs .{2} match any double character: aa, bb, &&, etc. (except newline) These examples demonstrate the three different usages of {}. With a single integer, {x} means "match exactly x occurrences of the previous character", with one integer and a comma, {x,} means "match x or more occurrences of the previous character", and with two comma-separated integers {x,y} means TEAM FLY PRESENTS Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com [...]... jobapp_action .php to send the data to mail_hr .php We can set the ACTION attribute of the jobapp_action .php' s form to "mail_hr .php" In addition, we need to pass the variables We could either build a query string as we did in Chapter 4[Variables], or we could use HIDDEN HTML input elements within the form Here we use the query-string method: .php > < ?php require ("common .php" );... "&avail=$avail" ; $URL = "mail_hr .php" $qs; echo (""); if ($submit) { echo (""); } ?> The function urlencode() is explained in Chapter 3 [Programming in Web Env] Though often overlooked by programmers new to PHP and web programming, the string functions... TEAM FLY PRESENTS Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Naturally, we will want to add this information to jobapp_action .php: .php > < ?php require ("common .php" ); $submit = 1; // Submit flag TEAM FLY PRESENTS Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com if (!$applicant) { $submit = 0; $applicant... significant problem with larger amounts of data, or data for which formatting needs to be preserved Fortunately, PHP provides a string function called nl2br() This function converts newline characters to tags, for just this sort of situation .php > < ?php require ("common .php" ); $submit = 1; // Submit flag if (!$applicant) { $submit = 0; $applicant = "Invalid Name";... input safe for databases, scripts, mail and other processes Suppose that we want the "Submit" button to e-mail the data to the human resources department We can create a PHP script called "mail_hr .php" : .php > < ?php $to = "hr@phopsbicycles.com"; $subj = "Online Application"; $header = "\nFrom: jobapp@taurix.com\n"; $body = "\nName: " quotemeta ($applicant) "\nPhone: " quotemeta... database products that may be case sensitive Experienced Perl programmers will also be interested to know that PHP has a set of Perl-compatible regular expression functions For more information, see http://www .php. net/manual/ref.pcre .php ereg() and eregi() The basic regular expression function in PHP is ereg(): int ereg(string pattern, string source, array [regs]); It returns a positive integer (equivalent... address: < ?php // common .php define ("COMPANY", "Phop's Bicycles"); define ("NL", "\n"); function check_email ($str) { // Returns 1 if a valid email, 0 if not if (ereg ("^.+@.+\\ +$", $str)) { return 1; } else { return 0; } } ?> Up until now, our HTML form has not included any TEXTAREA elements Let's introduce one to hold the mailing address of the applicant: .php > < ?php require... display correctly in the browser without being TEAM FLY PRESENTS Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com parsed or executed: .php > < ?php require ("common .php" ); $submit = 1; // Submit flag if (!$applicant) { $submit = 0; $applicant = "Invalid Name"; } if (!check_email ($email)) { $submit = 0; $email = "Invalid E-mail Address";... hold the mailing address of the applicant: .php > < ?php require ("common .php" ); ?> < ?php echo (COMPANY); ?> Job Application Are you looking for an exciting career in the world of cyclery? Look no further! Please enter your name (required): Please enter... Handling and Data Storage This chapter introduces two topics we need to understand if we wish to store data from our PHP pages persistently PHP provides functions for accessing non-relational databases and for working with the file system These functions allow us to store data which our PHP pages generate, or which they need to access, in text files or in simple databases In the second half of this chapter, . 3rd char to 3rd-from-last echo (substr("Christopher", 2, -3) ); // Prints 'ristop' // From 6th-from-last to 3rd-from-last echo (substr("Christopher", -6, -3) );. beginning at the 3rd-from-last echo (substr("Christopher", -3) ); // Prints 'her' // The 3rd, 4th, and 5th chars echo (substr("Christopher", 2, 3) ); // Prints. variables: $ch3_title = "Bicycle Safety"; $ch3_pg = 83; $ch4_title = "Repairs and Maintenance"; $ch4_pg = 115; // Print the TOC printf ("%' 40.40s%'.3d%s",