Sams Teach Yourself PHP, MySQL and Apache in 24 Hours phần 6 pot

73 305 0
Sams Teach Yourself PHP, MySQL and Apache in 24 Hours phần 6 pot

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

print "$membership<br>"; // prints "mz02xyz" PHP also provides a case function that has a useful cosmetic purpose. The ucwords() function makes the first letter of every word in a string uppercase. In the following snippet, we make the first letter of every word in a user-submitted string uppercase: $full_name = "violet elizabeth bott"; $full_name = ucwords($full_name); print $full_name; // prints "Violet Elizabeth Bott" Although this function makes the first letter of each word uppercase, it does not touch any other letters. So if the user had had problems with her Shift key in the previous example and submitted VIolEt eLIZaBeTH bOTt , our approach would not have done much to fix the string. We would have ended up with VIolEt ELIZaBeTH BOTt , which isn't much of an improvement. We can deal with this problem by making the submitted string lowercase with strtolower() before invoking ucwords() : $full_name = "VIolEt eLIZaBeTH bOTt"; $full_name = ucwords(strtolower($full_name)); print $full_name; // prints "Violet Elizabeth Bott" Wrapping Text with wordwrap() and nl2br() When you present plain text within a Web page, you are often faced with the problem that newlines are not displayed, and your text runs together into a featureless blob. The nl2br() function is a convenience method that converts every newline into an HTML break. So $string = "one line\n"; $string .= "another line\n"; $string .= "a third for luck\n"; print nl2br($string); will print one line<br /> another line<br /> a third for luck<br /> Notice that the <br> tags are output in XHTML-compliant form. This feature was introduced in PHP 4.0.5. The nl2br() function is great for honoring newlines that are already in the text you are converting. Occasionally, though, you may want to add arbitrary line breaks to format a column of text. The wordwrap() function is perfect for this task. wordwrap() requires one argument: the string to be transformed. By default, wordwrap() wraps lines every 75 characters and uses '\n ' as its line break character. So the code snippet $string = "Given a long line, wordwrap() is useful as a means of "; $string .= "breaking it into a column and thereby making it easier to read"; print wordwrap($string); would output Given a long line, wordwrap() is useful as a means of breaking it into a column and thereby making it easier to read Because the lines are broken with the character '\n ', the formatting does not show up in HTML mode, of course. wordwrap() has two more optional arguments: a number representing the maximum number of characters per line and a string representing the end of line string you would like to use. So applying the function call print wordwrap( $string, 24, "<br>\n" ); to our $string variable, our output would be Given a long line,<br> wordwrap() is useful as<br> a means of breaking it<br> into a column and<br> thereby making it easier<br> to read The wordwrap() function doesn't automatically break at your line limit if a word has more characters than the limit. You can, however, use an optional fourth argument to enforce such a break. The argument should be a positive integer. So using wordwrap() in conjunction with the fourth argument, we can now wrap a string, even where it contains words that extend beyond the limit we are setting. This snippet $string = "As usual you will find me at http://www.witteringonaboutit.com/"; $string .= "chat/eating_green_cheese/forum.php. Hope to see you there!"; print wordwrap( $string, 24, "<br>\n", 1 ); will output As usual you will find<br> me at<br> http://www.witteringonab<br> outit.com/chat/eating_gr<br> een_cheese/forum.php.<br> Hope to see you there! instead of As usual you will find<br> me at<br> http://www.witteringonaboutit.com/chat/eating_green_cheese/forum.php. <br> Hope to see you there! Breaking Strings into Arrays with explode() The delightfully named explode() function is similar in some ways to strtok() . But explode() will break up a string into an array, which you can then store, sort, or examine as you want. The explode() function requires two arguments: the delimiter string that you want to use to break up the source string and the source string itself. The function optionally accepts a third argument, which will determine the maximum number of pieces the string can be broken into. The delimiter string can include more than one character, all of which will form a single delimiter (unlike multiple delimiter characters passed to strtok() , each of which will be a delimiter in its own right). The following snippet breaks up a date and stores the result in an array: $start_date = "2002-01-12"; $date_array = explode("-", $start_date); // $date[0] == "2002" // $date[1] == "01" // $date[2] == "12" Now that your head is filled with PHP string functions, let's move on to MySQL string functions, many of which perform the same tasks. [ Team LiB ] [ Team LiB ] Frequently Used String Functions in MySQL MySQL's built-in string-related functions can be used several ways. You can use functions in SELECT statements without specifying a table to retrieve a result of the function. Or you can use functions to enhance your SELECT results by concatenating two fields to form a new string. Even if you never use these functions in your applications, it's good to know they exist, and, if nothing else, you'll get some good practice in this hour using the MySQL monitor's command-line interface. Length and Concatenation Functions The group of length and concatenation functions focuses on the length of strings and concatenating strings together. Length-related functions include LENGTH() , OCTET_LENGTH() , CHAR_LENGTH() , and CHARACTER_LENGTH() , which do virtually the same thing—count characters in a string. mysql> select length('This is cool!'); + + | LENGTH('This is cool!') | + + | 13 | + + 1 row in set (0.00 sec) The fun begins with the CONCAT() function, which is used to concatenate two or more strings: mysql> select concat('My', 'S', 'QL'); + + | CONCAT('My', 'S', 'QL') | + + | MySQL | + + 1 row in set (0.00 sec) Imagine using this function with a table containing names, split into firstname and lastname fields. Instead of using two strings, use two field names to concatenate the firstname and the lastname fields. By concatenating the fields, you reduce the lines of code necessary to achieve the same result in your application: mysql> select concat(firstname, lastname) from table_name; + + | CONCAT(firstname, lastname) | + + | JohnSmith | | JaneSmith | | JimboJones | | AndySmith | | ChrisJones | | AnnaBell | | JimmyCarr | | AlbertSmith | | JohnDoe | + + 9 rows in set (0.00 sec) If you're using a field name and not a string in a function, don't enclose the field name within quotation marks. If you do, MySQL will interpret the string literally. In the CONCAT() example, you would get the following result: mysql> select concat('firstname', 'lastname') FROM table_name; + + | CONCAT('firstname', 'lastname') | + + | firstnamelastname | | firstnamelastname | | firstnamelastname | | firstnamelastname | | firstnamelastname | | firstnamelastname | | firstnamelastname | | firstnamelastname | | firstnamelastname | + + 9 rows in set (0.00 sec) The CONCAT() function would be useful if there were some sort of separator between the names, and that's where the next function comes in: CONCAT_WS() . As you may have figured out, CONTACT_WS() stands for "concatenate with separator." The separator can be anything you choose, but the following example uses whitespace: mysql> select concat_ws(' ', firstname, lastname) FROM table_name; + + | CONCAT_WS(' ', firstname, lastname) | + + | John Smith | | Jane Smith | | Jimbo Jones | | Andy Smith | | Chris Jones | | Anna Bell | | Jimmy Carr | | Albert Smith | | John Doe | + + 9 rows in set (0.00 sec) If you want to shorten the width of your result table, you can use AS to name the custom result field: mysql> select concat_ws(' ', firstname, lastname) AS fullname FROM table_name; + + | fullname | + + | John Smith | | Jane Smith | | Jimbo Jones | | Andy Smith | | Chris Jones | | Anna Bell | | Jimmy Carr | | Albert Smith | | John Doe | + + 9 rows in set (0.00 sec) Trimming and Padding Functions MySQL provides several functions for adding and removing extra characters (including whitespace) from strings. The RTRIM() and LTRIM() functions remove whitespace from either the right or left side of a string: mysql> select rtrim('stringstring '); + + | RTRIM('stringstring ') | + + | stringstring | + + 1 row in set (0.00 sec) mysql> select ltrim(' stringstring'); + + | LTRIM(' stringstring') | + + | stringstring | + + 1 row in set (0.00 sec) You may have padded strings to trim if the string is coming out of a fixed-width field, and either doesn't need to carry along the additional padding or is being inserted into a varchar or other non–fixed-width field. If your strings are padded with a character besides whitespace, use the TRIM() function to name the characters you want to remove. For example, to remove the leading "X" characters from the string XXXneedleXXX , use mysql> select trim(leading 'X' from 'XXXneedleXXX'); + + | TRIM(LEADING 'X' from 'XXXneedleXXX') | + + | needleXXX | + + 1 row in set (0.00 sec) Use TRAILING to remove the characters from the end of the string: mysql> select trim(trailing 'X' from 'XXXneedleXXX'); + + | TRIM(TRAILING 'X' from 'XXXneedleXXX') | + + | XXXneedle | + + 1 row in set (0.00 sec) If neither LEADING nor TRAILING is indicated, both are assumed: mysql> select trim('X' from 'XXXneedleXXX'); + + | TRIM('X' from 'XXXneedleXXX') | + + | needle | + + 1 row in set (0.00 sec) Just like RTRIM() and LTRIM() remove padding characters, RPAD() and LPAD() add characters to a string. For example, you may want to add specific identification characters to a string that is part of an order number, in a database used for sales. When you use the padding functions, the required elements are the string, the target length, and the padding character. For example, pad the string needle with the X character until the string is 10 characters long: mysql> select rpad('needle', 10, 'X'); + + | RPAD('needle', 10, 'X') | + + | needleXXXX | + + 1 row in set (0.00 sec) mysql> select lpad('needle', 10, 'X'); + + | LPAD('needle', 10, 'X') | + + | XXXXneedle | + + 1 row in set (0.00 sec) Location and Position Functions The group of location and position functions is useful for finding parts of strings within other strings. The LOCATE() function returns the position of the first occurrence of a given substring within the target string. For example, you can look for a needle in a haystack: mysql> select locate('needle', 'haystackneedlehaystack'); + + | LOCATE('needle', 'haystackneedlehaystack') | + + | 9 | + + 1 row in set (0.00 sec) The substring needle begins at position 9 in the target string. If the substring cannot be found in the target string, MySQL returns 0 as a result. Unlike position counting within most programming languages, which starts at 0, position counting using MySQL starts at 1. An extension of the LOCATE() function is to use a third argument for starting position. If you start looking for needle in haystack before position 9, you'll receive a result. Otherwise, because needle starts at position 9, you'll receive a 0 result if you specify a greater starting position: mysql> select locate('needle', 'haystackneedlehaystack',6); + + | LOCATE('needle', 'haystackneedlehaystack',9) | + + | 9 | + + 1 row in set (0.00 sec) mysql> select locate('needle', 'haystackneedlehaystack',12); + + | LOCATE('needle', 'haystackneedlehaystack',12) | + + | 0 | + + 1 row in set (0.00 sec) Substring Functions If your goal is to extract a substring from a target string, several functions fit the bill. Given a string, starting position, and length, you can use the SUBSTRING() function. This example gets three characters from the string MySQL , starting at position 2: [...]... row in set (0.00 sec) The following example gets a string representation of the octal value of the integer 568 95: mysql> select oct( 568 95); + + | OCT( 568 95) | + + | 157077 | + + 1 row in set (0.00 sec) The following example gets a string representation of the hexadecimal value of the integer 568 95: mysql> select hex( 568 95); + + | HEX( 568 95) | + + | DE3F | + + 1 row in set... user submits and print the result back to the browser Check that the user's email address contains the @ symbol and print a warning otherwise 2 Create an array of doubles and integers Loop through the array converting each element to a floating-point number with a precision of 2 Right-align the output within a field of 20 characters 3 Using both PHP and MySQL, practice using functions within functions,... converting from, and the base you're converting to For example, to convert the integer 568 95 from base 10 to base 8 and return its value, use mysql> select conv( 568 95,10,8); + + | CONV( 568 95,10,8) | + + | 157077 | + + 1 row in set (0.00 sec) This result is equivalent to the 16, use OCT() function Similarly, to convert an integer from base 10 to base mysql> select conv( 568 95,10, 16) ;... 4: A4: 5: A5: 6: A6: What function would you use to extract a substring from a string? The substr() function extracts and returns a substring How might you remove whitespace from the beginning of a string? The ltrim() function removes whitespace from the start of a string How would you break up a delimited string into an array of substrings? The explode() function splits up a string into an array 7:... next three functions return string representations of binary, octal, and hexadecimal values Like the ASCII() function, the BIN() , OCT() , and HEX() functions do not require a table selection but return values without a specified table The following example gets a string representation of the binary value of the integer 568 95: mysql> select bin( 568 95); + + | BIN( 568 95) | + + | 1101111000111111... dependent on a key Think about removing repeated data and you'll find your answer—instructors Inevitably, an instructor will teach more than one class However, CourseInstructor is not a key of any sort So, if you break out this information and create a separate table purely for the sake of efficiency and maintenance (as shown in Figure 14.11), that's the third normal form Figure 14.11 Taking your tables... than 60 string functions! You can read about them all in the PHP Manual online at http://www.php.net/manual/ref.strings.php Q2: Can I use multiple functions in one statement, such as making a concatenated string all uppercase? A2: Sure—just be mindful of your opening and closing parentheses This example shows how to uppercase the concatenated first and last names from the master name table: mysql> ... CONV( 568 95,10, 16) | + -+ | DE3F | + -+ 1 row in set (0.00 sec) This result is equivalent to the HEX() function You can also convert from base 8 to base 16: mysql> select conv(157077,8, 16) ; + -+ | CONV(157077,8, 16) | + -+ | DE3F | + -+ 1 row in set (0.00 sec) And so on The minimum base is 2 and the maximum base is 36 Another function for working with characters and. .. of the strings in your PHP scripts You learned how to format strings with printf() and sprint() You should be able to use these functions both to create strings that transform data and lay it out You learned about functions that investigate strings You should be able to discover the length of a string with strlen(), determine the presence of a substring with strpos(), or extract a substring with substr()... on strings If you have strings in MySQL you want to concatenate or for which you want to count characters, you can use functions such as CONCAT(), CONCAT_WS() , and LENGTH() To pad or remove padding from strings, use RPAD(), LPAD(), TRIM(), LTRIM(), and RRIM() to get just the strings you want You can also find the location of a string within another, or to return a part of a given string, using the . + 9 rows in set (0.00 sec) Trimming and Padding Functions MySQL provides several functions for adding and removing extra characters (including whitespace) from strings. The RTRIM() and LTRIM(). string: mysql& gt; select rtrim('stringstring '); + + | RTRIM('stringstring ') | + + | stringstring | + + 1 row in set (0.00 sec) mysql& gt; select ltrim(' stringstring'); +. 'QL') | + + | MySQL | + + 1 row in set (0.00 sec) Imagine using this function with a table containing names, split into firstname and lastname fields. Instead of using two strings, use two field

Ngày đăng: 13/08/2014, 21:21

Từ khóa liên quan

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan