1. Trang chủ
  2. » Công Nghệ Thông Tin

Tài liệu PHP and MySQL by Example- P4 pptx

50 475 0

Đ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

Thông tin cơ bản

Định dạng
Số trang 50
Dung lượng 1,62 MB

Nội dung

Figure 6.6. Precision of numbers. Output from Example 6.6. In the next example, printf() will format a string and a number. Example 6.7. <?php $product_name = "Black shoes"; $product_price= 249.95; 1 printf( "Product %s will cost %6.2f dollars", $product_name, $product_price ); ?> Explanation ! "#$%30,*(0+%)*(',/%30,*.',)%*:0%&0(<.*%)6$3'&'$()8% %s %.,-% %6.2d 4%"#$%1.('.2+$% $product_name 8%*#$%&'()*%.(/7<$,*8%:'++%2$%6(',*$-%.330(-',/%*0%*#$%&'()*% &0(<.*%)6$3'&'$(8% %s 8%.%)*(',/4%"#$%)$30,-%.(/7<$,*8% $product_price 8%:'++%2$% 6(',*$-%.330(-',/%*0%*#$%)$30,-%&0(<.*%)6$3'&'$(8% %6.2f 4%I,%*#')%3.)$8% 6 %($&$()%*0% *0*.+%,7<2$(%0&%-'/'*)%*#.*%*#')%,7<2$(%3.,%03376=%.,-% .2 %)6$3&''$)%.%6($3')'0,% 0&%5%6+.3$)%*0%*#$%('/#*%0&%*#$%-$3'<.+%60',*4%I&%*#$%,7<2$(%')%+.(/$(%*#.,%D8% printf() %:'++%,0*%*(7,3.*$%'*4%I*%R7)*%<'/#*%,0*%+00A%*#$%:.=%=07%#.-% $,1')'0,$-%'*4%B$$%C'/7($%D4Z4 % Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Figure 6.7. Output from Example 6.7. Table 6.2 shows the most common format specifiers. The format specifier can be modified by placing specifying a precision, left or right justification, padding characters, and so on, as shown in Table 6.3. Table 6.3. Modifiers for the printf() Format Specifier Modifier Example Format . %.2f B6$3'&'$)%.%6($3')'0,%0&%*:0%-'/'*)%*0%*#$%('/#*%0&%*#$%-$3'<.+%60',*%',% .%&+0.*',/O60',*%,7<2$( integer %8d B6$3'&'$)%,7<2$(%0&%3#.(.3*$()%&0(%*#')%.(/7<$,*%*0%2$%-')6+.=$-@% $4/48%&'$+-%:'-*#%0&%[%-'/'*) - %-8.2f % %- 30s S.7)$)%*#$%&0(<.**',/%*0%2$%+$&*%R7)*'&'$-@%$4/48%+$&*OR7)*'&'$-%&+0.*',/O 60',*%,7<2$(%:'*#%.%&'$+-%:'-*#%0&%[8%0(%+$&*OR7)*'&'$-%P\O)6.3$%)*(',/ 0 %08d F.-)%*#$%,7<2$(%:'*#%\) % There are some other formatting functions similar to the printf function differing primarily in how the output is displayed. The sprintf() Function This function is identical to printf() except that instead of displaying the formatted string, sprintf() returns the formatted string so that you can assign it to a variable. See Example 6.8. Format string sprintf ( string format [, mixed args [, mixed .]] ) % Example: $formatted_string=sprintf("%s owes me %.2f dollars\n", $name, $amount); Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Example 6.8. <?php $product_name = "Purple Dress"; $product_price = 199.95; 1 $output = sprintf( "Product <b>%s</b> will cost <u>$%6.2f</u> + tax", $product_name, $product_price ); ?> <html><title>The sprintf() Function</title></head> <body bgcolor="#EBF4F3"> <h1>Shopping Cart Checkout</h1> <font face="Arial"> 2 <?= $output ?> </font></body> Explanation ! "#$%&'()*%6.(.<$*$(%*0%*#$% sprintf() %&7,3*'0,%')%*#$%30,*(0+%)*(',/%)6$3'&=',/% #0:%*0%6(',*%*#$%)*(',/4%"#$%*:0%.(/7<$,*)%&0++0:',/%*#$%30,*(0+%)*(',/%.($%*#$% .3*7.+%1.('.2+$)8% $product_name %.,-% $product_price 8%*#.*%30(($)60,-%*0%$.3#% 0&%*#$%&0(<.*%30,1$()'0,%)6$3'&'$()8% %s %.,-% %6.2f 8%',%*7(,4%"#$% sprintf() % &7,3*'0,%:'++%&0(<.*%*#$%)*(',/%.,-%.))'/,%'*%*0%*#$%1.('.2+$8%3.++$-% $output variable 4 5 G$($%:$%7)$%*#$%)#0(*%&0(<%*0%6(',*%07*%.%1.+7$%0&%*#$%1.('.2+$% $output %',*0%*#$% G"]^%2(0:)$(8%.)%)#0:,%',%C'/7($%D4[4 % Figure 6.8. The sprintf() function. Output from Example 6.8. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. The fprintf() Function Whereas the printf() function writes the output to the standard output stream (the browser), the fprintf() function sends the output to any output stream specified, usually a file. Format int fprintf ( resource handle, string format [, mixed args [, mixed .]] ) % Example: sprintf($filehandle, "%04d-%02d-%02d", $year, $month, $day); For more information on streams and files, see Chapter 11, “Files and Directories.” 6.2.2. Formatting Numbers and Money Putting commas or spaces in numbers or printing out the dollar value of money causes a number to become a string and can be handled with printf(). PHP also provides two special functions, the number_format() function and the money_format() function. The number_format() Function PHP provides the number_format() function to format a number with grouped thousands. There are three ways to use this function. You can specify no arguments, two arguments, or four arguments, but not three arguments. When only one number is specified, the number returned will be a whole number. It will include commas for every group of thousands, but the fractional part will be truncated along with the decimal point. If the first number after the decimal point is 5 or higher, the new number will be rounded up. If two numbers are specified, the second number will indicate the number of decimal places to format, such as two places after the decimal point for a dollar and cents amount. Groups of thousands will still be comma-separated. The third way to use this function is to specify the number to format, number of decimal places, as well as the characters to use for separating groups of thousands, as well as the decimal point. This is useful for locales that use number formats different than North American formats. Example 6.9 illustrates how to use the number_format() function. Figure 6.9 shows the output, three formatted numbers. Format string number_format ( float number [, int decimals [, string dec_point, string thousands_sep]] ) % Example: $number=123456.5456 $new_string = number_format($number); // Returns: 123,457 $new_string = number_format($number, 2); // Returns: 123,456.55 $num_francais = number_format($number, 2, ',', ' '); // Returns 1 234,56 Example 6.9. <?php $number = 7634.887; // American format is the default: 7,643.89 1 $us_format = number_format($number, 2); print "$us_format<br />"; // French format: 7 634,89 2 $french_format = number_format($number, 2, ',', ' '); print "$french_format<br />"; // American format without thousands separator: 7634.89 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 3 $us_format2 = number_format($number, 2, '.', ''); print "$us_format2<br />"; ?> Explanation ! "#')%')%*#$%-$&.7+*%&0(<.*%&0(%*#$%X4B4%,7<2$()4%"#$%)$30,-%6.(.<$*$(%)6$3'&'$)% *#$%,7<2$(%0&%-$3'<.+%6+.3$)8%',%*#')%3.)$%*:04% number_format() %.7*0<.*'3.++=% (07,-)%*0%*:0%-$3'<.+)%',%*#')%3.)$4 5 "#')%+',$%)#0:)%#0:%*0%7)$%*#$% number_format() %&7,3*'0,%:'*#%&07(% .(/7<$,*)4%"#$%&'()*%*:0%.(/7<$,*)%.($%*#$%).<$%.)%',%*#$%6($1'07)%+',$E%*#$% ,7<2$(%*0%2$%&0(<.**$-%.,-%*#$%,7<2$(%0&%-$3'<.+%6+.3$)4%"#$%*#'(-% .(/7<$,*%)6$3'&'$)%*#$%)$6.(.*0(%3#.(.3*$(%*0%2$%7)$-%&0(%-$3'<.+%6+.3$)4%I,% C(.,3$8%.%30<<.%')%7)$-%(.*#$(%*#.,%.%-$3'<.+%60',*4%"#$%&07(*#%.(/7<$,*%')% *#$%)$6.(.*0(%&0(%*#$%*#07).,-)%.,-%#$($%:$%7)$%.%)',/+$%)6.3$8%(.*#$(%*#.,%.% 30<<.8%*#$%*#07).,-)%)$6.(.*0(%30<<0,+=%7)$-%',%<0)*%_7(06$.,%307,*('$)4 P "#')%$9.<6+$%')%1$(=%)'<'+.(%*0%*#$%6($1'07)%0,$4%"#$%<.',%-'&&$($,3$%')%*#.*% *#$%&07(*#%.(/7<$,*%')%$<6*=8%)6$3'&=',/%,0%3#.(.3*$(%&0(%*#$%*#07).,-)% )$6.(.*0(4 Figure 6.9. The number_format() function. The output from Example 6.9. % The money_format() Function The money_format() function formats a number as a string representing currency. Because this function depends on a C library function called strfmon(), it cannot be implemented on your system if you are using Windows. This function can format money for any number of locales and comes with a large array of formatting specifications. It works with negative numbers, deals with left and right precision, padding, and so on, similar to the printf() function. For a complete discussion on how to use this function, see the PHP manual. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Format string money_format ( string format, float number ) % Example: setlocale(LC_MONETARY, 'en_US'); echo money_format('%i', $number) . "\n"; // USD 1,234.56 6.2.3. Finding the Length of a String The strlen() Function To find the length of a string (how many characters there are in the string), PHP provides the strlen() function. See Example 6.10. Format int strlen ( string string ) % Example: $length = strlen("Hello, world\n"); Example 6.10. <html><head><title>Finding the Length of a String</title> </head> <body bgcolor="lightgreen"> <font size="+1"> <?php 1 $string="\t\tHello, world."; 2 $length=strlen($string); print nl2br("There are $length characters in \"$string\""); ?> </body> </html> Explanation ! "#$%1.('.2+$8% $string 8%30,*.',)%.%)*(',/%0&%3#.(.3*$()%',3+7-',/%*#$%*.2%3#.(.3*$(4 5 "#$% strlen() %&7,3*'0,%($*7(,)%*#$%,7<2$(%0&%3#.(.3*$()%',% $string 4%"#$%*.2%3#.(.3*$(% -0$),H*%)#0:%76%',%*#$%2(0:)$(8%27*%2=%1'$:',/%*#$%)07(3$%30-$8%=07%3.,%)$$%'*8%.)%)#0:,% ',%C'/7($%D4!\4 % % % % % % % % % % Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. % Figure 6.10. The strlen() function. Viewing the source code from Example 6.10. % 6.2.4. Finding the Number of Words in a String The str_word_count() Function The str_word_count() function returns information about the words that make up a string. A word is defined as a locale-dependent (Germany, U.S., etc.) string containing alphabetic characters, which also can contain, but not start with ' and - characters. By default, the str_word_count() function counts the number of words in a string. An optional third argument can be one of the three values shown in Table 6.4. Table 6.4. Optional Third Arguments to the str_word_count() Function Argument What+It+Returns 0 `$*7(,)%*#$%,7<2$(%0&%:0(-)%&07,-4 1 `$*7(,)%.,%.((.=%30,*.',',/%.++%*#$%:0(-)%&07,-%',)'-$%*#$%)*(',/4 2 `$*7(,)%.,%.))03'.*'1$%.((.=8%:#$($%*#$%A$=%')%*#$%,7<$('3%60)'*'0,%0&%*#$%:0(-% ',)'-$%*#$%)*(',/%.,-%*#$%1.+7$%')%*#$%.3*7.+%:0(-%'*)$+&4 % An optional fourth argument, charlist, allows you to add characters that will be accepted as part of a word, such as foreign accent marks, ellipses, long dashes, or hyphens. Format mixed str_word_count(string string [, int format [, string charlist]] ) % Example: $num_words = str_word_count("Happy New Year, to you!"); print_r(str_word_count("Solstickan såljes till förmån för barn och gamla",1, "åÅö"); Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 6.2.5. Changing the Case of Strings If you are validating an e-mail address or the abbreviation for a state, such as CA or MD, you might want to convert the entire string into lowercase letters before proceding, or you might want to convert just the first character in a string, as in Mrs. or Dr. PHP provides functions for changing the case of the characters in a string, as shown in Table 6.5. Table 6.5. Functions That Change the Case of Strings Function What+It+Does strtoupper() S0,1$(*)%.%)*(',/%*0%766$(3.)$%+$**$() strtolower() S0,1$(*)%.%)*(',/%*0%+0:$(3.)$%+$**$() ucfirst() S0,1$(*)%*#$%&'()*%+$**$(%',%.%)*(',/%*0%766$(3.)$ ucwords() S0,1$(*)%*#$%&'()*%+$**$(%',%$.3#%:0(-%0&%.%)*(',/%*0%766$(3.)$ mb_convert_case() S0,1$(*)%3.)$%0&%.%)*(',/%2.)$-%0,%X,'30-$%3#.(.3*$(%6(06$(*'$) % The strtoupper() and strtolower() Functions The functions strtoupper() and strtolower() are used to convert the case of characters in a string from upper- to lowercase or vice versa. strtoupper() takes a string and returns a new string with every single letter capitalized. strtolower() returns a new string with every character converted to lowercase. Format string strtoupper ( string ) string strtolower ( string ) % Example: $newstring=strtoupper("merry christmas"); // returns "MERRY CHRISTMAS" $newstring=strtolower("HAPPY NEW YEAR"); // returns "happy new year" Example 6.11. <?php $text = "Marko@Marakana.Com"; 1 print strtolower( $text . "<br />" ); //prints: marko@marakana.com 2 print strtoupper( $text . "<br />" ); //prints: MARKO@MARAKANA.COM ?> Explanation ! "#')%+',$%:'++%R7)*%07*67*%*#$%*$9*%30,1$(*$-%.++%',%+0:$(3.)$4 5 strtoupper() %-0$)%*#$%0660)'*$8%30,1$(*',/%*#$%*$9*%',*0%766$(3.)$%+$**$()4 The ucfirst() and ucwords() Functions If you want to change just the first character in a string to uppercase, PHP provides the ucfirst() and ucwords() functions. The ucfirst() function converts the first character of a string to uppercase. The ucwords() function capitalizes first letters of all the words in the string. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Format string ucfirst ( string str ) string ucword( string str) % Example: // Returns "San jose, california" $newstring=ucfirst("san jose, california"); // Returns "San Jose, California" $newstring=ucwords("san jose, california"); Example 6.12. <?php $text = "it rains in spain"; 1 print ucfirst( $text . "<br />" ); // prints: It rains in spain 2 print ucwords( $text . "<br />" ); // prints: It Rains In Spain ?> Explanation ! "#')%+',$%07*67*)% It rains in spain 4%"#$% ucfirst() %&7,3*'0,%($*7(,)%*#$% )*(',/%:'*#%*#$%&'()*%+$**$(%3.6'*'.+'a$-4%B$$%C'/7($%D4!!4 5 "#$% ucwords() %&7,3*'0,%3.6'*.+'a$)%*#$%&'()*%+$**$(%',%$.3#%:0(-%0&%*#$%)*(',/8% +'A$%*#$%*'*+$%',%.%200A8%&0(%$9.<6+$4%"#$%07*67*%:'++%2$% It Rains In Spain 8%.)% )#0:,%',%C'/7($%D4!!4 % Figure 6.11. The ucfirst() and ucwords() functions. The mb_convert_case() Function The mb_convert_case() function is like strtolower() and strtoupper() but is not locale dependent; that is, it bases its conversion on Unicode characters rather than just ASCII, which means letters containing the German umlaut, the Swedish ring, or French accent marks are folded (included) into case conversion. To specify the case, this function provides three modes: MB_CASE_UPPER, MB_CASE_LOWER, or MB_CASE_TITLE. You can also specify a supported character set to establish how the string will be encoded. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Table 6.6. Supported Character Sets Charset Aliases Description IBUO[[bcO ! IBU[[bcO! ?$)*$(,%_7(06$.,8%^.*',O! IBUO[[bcO !b IBU[[bcO !b ?$)*$(,%_7(06$.,8%^.*',Oc4%W--)%*#$%_7(0%)'/,8%C($,3#%.,-%C',,')#% +$**$()%<'))',/%',%^.*',O!JIBUO[[bcO!K X"CO[ % WBSII%30<6.*'2+$%<7+*'2=*$%[O2'*%X,'30-$ 36[DD '2<[DD8% [DD VUBO)6$3'&'3%S=('++'3%3#.()$*@%)7660(*$-%',%Q4P45 % Format string mb_convert_case ( string str, int mode [, string encoding] ) % Example: $string = "exit here!!"; echo mb_convert_case($string, MB_CASE_UPPER,"UTF-8"); // Returns: EXIT HERE!! $string = "förvaras oåtkomligt för barn"; echo mb_convert_case($string, MB_CASE_TITLE,"IS0-8859-15"); // Returns: Förvaras Oåtkomligt För Barn 6.2.6. Comparing Strings Does the password a user entered match the one on file? Does the user’s response compare to the expected answer? PHP provides a number of functions to make comparing strings relatively easy. To ensure you are always comparing strings, you should use string comparison functions rather than comparison operators because the functions always cast their arguments to strings before comparing them. Also keep in mind when comparing strings, that " hello" [1] is not the same as "hello" or "Hello", for example. PHP provides several functions to compare two strings, listed in Table 6.7. [1] You can use the trim() function to remove unwanted whitespace (See “The trim() Functions—trim(), ltrim(), chop, rtrim()” on page 182). Table 6.7. Return Value from Comparison Value What+It+Means 0 %Ja$(0K "#$%*:0%1.+7$)%.($%$;7.+ > 0 %J/($.*$(%*#.,%a$(0K T.+7$%*:0%')%/($.*$(%*#.,%1.+7$%0,$ < 0 %J+$))%*#.,%a$(0K T.+7$%0,$%')%/($.*$(%*#.,%1.+7$%*:0 % All string comparisons take at least two arguments and return a value based on comparing those arguments. The return value is always an integer that can be interpreted as shown in Table 6.7. Table 6.8 lists string comparison functions and how they compare two strings. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. [...]... Splitting a String PHP provides a number of functions to split strings The split() and spliti() functions split up a string and return an array The explode() function splits up a string by a specified delimiter and returns an array The implode() function takes an array and joins the elements together to form a string Because these functions require that you understand PHP arrays and regular expressions,... compares each character in the string alphabetically based on the system’s collating sequence Because PHP uses the ASCII collating sequence, an uppercase “A” is represented as decimal 65 and an uppercase “B” as decimal 66, and so on On the other hand, a lowercase “a” is 97 and a lowercase “b” is 98, and so on If you compare “A” to “a,” you can say that “A” is less than “a” because of their numeric representation... (see  Chapter  8) preg_split() Splits  up  a  string by  a  Perl-­‐compatible  regular  expression and  returns  an   array  of  substrings  (see  Chapter  12) explode() Splits  up  a  string by  another  string  (not  a  regular  expression) and  returns  an   array  (see  Chapter  8) implode() Joins  array  elements  together by  a  string and  returns  a  string   The strtok() Function The... arrays and regular expressions, they are covered in Chapter 8, “Arrays,” and Chapter 12, “Regular Expressions and Pattern Matching.” Table 6.9 provides the names of these functions, what they do, and where to find a complete discussion and examples Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark Table 6.9 PHP Functions for Splitting Strings Function What  It  Does split() Splits... second string, and 0 if they are equal Example 6.15 demonstrates how this function works Format int strncasecmp ( string str1, string str2, int length )   Example: // Compares first 4 characters in each string $number = strncasecmp("Homeland", "homeland", 4); Example 6.15 The strncasecmp() Function Comparing Strings by Limit of Characters < ?php 1 $str1="chronometer";... Search and Replace Searching and replacing text is a function you use commonly in a text editor PHP provides a set of functions to search for a string and replace it with a new one If you are trying to fine-tune your search pattern (e.g., search for all strings starting with a number or a lowercase letter), you have the option to use regular expressions, covered in Chapter 12, “Regular Expressions and. .. pronounciation rather than British English For example, “father” and “farther” do not sound the same in America, nor do “source” and “sauce,” or “tuba” and “tuber.” The only obvious difference between the two functions is that metaphone() is more precise in determining which words have the same pronunciation Example 6.17 demonstrates how to use the soundex() and metaphone() functions The output is diplayed in Figure... bgcolor="silver"> < ?php 1 $sound1 = "bald"; $sound2 = "bawled"; 2 $key1=soundex("$sound1"); $key2=soundex("$sound2"); if ($key1 == $key2){ print "The key values are: $key1 and $key2.\n"; print "\"$sound1\" and \"$sound2\" are homophones.\n"; 4 5 } $sound1 = "tuba"; $sound2 = "tuber"; if (metaphone($sound1) == metaphone($sound2)){ print "\"$sound1\" and \"$sound2\" are homonyms.\n";... Suppose you want to separate two blocks of text by a row of dashes PHP provides the str_repeat() function to repeat a string a specified number of times The first argument is the string that will be repeated and the second argument, called the multiplier, is the number of times you want to repeat it The multiplier must be greater than or equal to zero and if it is zero, an empty string will be returned... input, int multiplier)   Example: print str_repeat("-", 30); // prints 30 dashes 6.2.10 Trimming and Padding Strings PHP provides a set of functions that trim and pad strings Trimming means to remove excess or to prune, as in trimming your hair, your hedges, or your budget You might want to clean up a string by getting rid of excess whitespace (or some other character) from the beginning or end of the . that you understand PHP arrays and regular expressions, they are covered in Chapter 8, “Arrays,” and Chapter 12, “Regular Expressions and Pattern Matching.”. Because PHP uses the ASCII collating sequence, an uppercase “A” is represented as decimal 65 and an uppercase “B” as decimal 66, and so on. On the other hand,

Ngày đăng: 24/12/2013, 03:17

TỪ KHÓA LIÊN QUAN