PHP and MySQL by Example- P4

Chia sẻ: Thanh Cong | Ngày: | Loại File: PDF | Số trang:50

lượt xem

PHP and MySQL by Example- P4

Mô tả tài liệu
  Download Vui lòng tải xuống để xem tài liệu đầy đủ

Tham khảo tài liệu 'php and mysql by example- p4', công nghệ thông tin, kỹ thuật lập trình phục vụ nhu cầu học tập, nghiên cứu và làm việc hiệu quả

Chủ đề:

Nội dung Text: PHP and MySQL by Example- P4

  1. 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. Explanation 1 The  control  string  contains  two  format  specifiers,  %s  and  %6.2d.  The  variable   $product_name,  the  first  argument,  will  be  printed  according  to  the  first   format  specifier,  %s,  a  string.  The  second  argument,  $product_price,  will  be   printed  according  to  the  second  format  specifier,  %6.2f.  In  this  case,  6  refers  to   total  number  of  digits  that  this  number  can  occupy  and  .2  specfiies  a  precision   of  2  places  to  the  right  of  the  decimal  point.  If  the  number  is  larger  than  6,   printf()  will  not  truncate  it.  It  just  might  not  look  the  way  you  had   envisioned  it.  See  Figure  6.7.   Please purchase PDF Split-Merge on to remove this watermark.
  2. 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 Specifies  a  precision  of  two  digits  to  the  right  of  the  decimal  point  in   a  floating-­‐point  number integer %8d Specifies  number  of  characters  for  this  argument  to  be  displayed;   e.g.,  field  width  of  8  digits - %-8.2f  %- Causes  the  formatting  to  be  left  justified;  e.g.,  left-­‐justified  floating-­‐ 30s point  number  with  a  field  width  of  8,  or  left-­‐justified  30-­‐space  string 0 %08d Pads  the  number  with  0s   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 to remove this watermark.
  3. Example 6.8. The sprintf() Function Shopping Cart Checkout 2 Explanation 1 The  first  parameter  to  the  sprintf()  function  is  the  control  string  specifying   how  to  print  the  string.  The  two  arguments  following  the  control  string  are  the   actual  variables,  $product_name  and  $product_price,  that  correspond  to  each   of  the  format  conversion  specifiers,  %s  and  %6.2f,  in  turn.  The  sprintf()   function  will  format  the  string  and  assign  it  to  the  variable,  called  $output variable. 2 Here  we  use  the  short  form  to  print  out  a  value  of  the  variable  $output  into  the   HTML  browser,  as  shown  in  Figure  6.8.   Figure 6.8. The sprintf() function. Output from Example 6.8. Please purchase PDF Split-Merge on to remove this watermark.
  4. 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.
  5. 3 $us_format2 = number_format($number, 2, '.', ''); print "$us_format2"; ?> Explanation 1 This  is  the  default  format  for  the  U.S.  numbers.  The  second  parameter  specifies   the  number  of  decimal  places,  in  this  case  two.  number_format()  automatically   rounds  to  two  decimals  in  this  case. 2 This  line  shows  how  to  use  the  number_format()  function  with  four   arguments.  The  first  two  arguments  are  the  same  as  in  the  previous  line:  the   number  to  be  formatted  and  the  number  of  decimal  places.  The  third   argument  specifies  the  separator  character  to  be  used  for  decimal  places.  In   France,  a  comma  is  used  rather  than  a  decimal  point.  The  fourth  argument  is   the  separator  for  the  thousands  and  here  we  use  a  single  space,  rather  than  a   comma,  the  thousands  separator  commonly  used  in  most  European  countries. 3 This  example  is  very  similar  to  the  previous  one.  The  main  difference  is  that   the  fourth  argument  is  empty,  specifying  no  character  for  the  thousands   separator. 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 to remove this watermark.
  6. 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. Finding the Length of a String Explanation 1 The  variable,  $string,  contains  a  string  of  characters  including  the  tab  character. 2 The  strlen()  function  returns  the  number  of  characters  in  $string.  The  tab  character   doesn’t  show  up  in  the  browser,  but  by  viewing  the  source  code,  you  can  see  it,  as  shown   in  Figure  6.10.                     Please purchase PDF Split-Merge on to remove this watermark.
  7.   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 Returns  the  number  of  words  found. 1 Returns  an  array  containing  all  the  words  found  inside  the  string. 2 Returns  an  associative  array,  where  the  key  is  the  numeric  position  of  the  word   inside  the  string  and  the  value  is  the  actual  word  itself.   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 to remove this watermark.
  8. 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() Converts  a  string  to  uppercase  letters strtolower() Converts  a  string  to  lowercase  letters ucfirst() Converts  the  first  letter  in  a  string  to  uppercase ucwords() Converts  the  first  letter  in  each  word  of  a  string  to  uppercase mb_convert_case() Converts  case  of  a  string  based  on  Unicode  character  properties   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. Explanation 1 This  line  will  just  output  the  text  converted  all  in  lowercase. 2 strtoupper()  does  the  opposite,  converting  the  text  into  uppercase  letters. 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 to remove this watermark.
  9. 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. Explanation 1 This  line  outputs  It rains in spain.  The  ucfirst()  function  returns  the   string  with  the  first  letter  capitialized.  See  Figure  6.11. 2 The  ucwords()  function  capitalizes  the  first  letter  in  each  word  of  the  string,   like  the  title  in  a  book,  for  example.  The  output  will  be  It Rains In Spain,  as   shown  in  Figure  6.11.   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 to remove this watermark.
  10. Table 6.6. Supported Character Sets Charset Aliases Description ISO-­‐8859-­‐ ISO8859-­‐1 Western  European,  Latin-­‐1 1 ISO-­‐8859-­‐ ISO8859-­‐ Western  European,  Latin-­‐9.  Adds  the  Euro  sign,  French  and  Finnish   15 15 letters  missing  in  Latin-­‐1(ISO-­‐8859-­‐1) UTF-­‐8   ASCII  compatible  multibyte  8-­‐bit  Unicode cp866 ibm866,   DOS-­‐specific  Cyrillic  charset;  supported  in  4.3.2 866   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  (zero) The  two  values  are  equal > 0  (greater  than  zero) Value  two  is  greater  than  value  one < 0  (less  than  zero) Value  one  is  greater  than  value  two   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 to remove this watermark.
  11. Table 6.8. String Comparison Function What  It  Does strcmp() Compares  two  strings  (case  sensitive) strcasecmp() Compares  two  strings  (not  case  sensitive) strnatcmp(str1, str2); Compares  two  strings  in  ASCII  order,  but  any  numbers  are   compared  numerically strnatcasecmp(str1, Compares  two  strings  in  ASCII  order,  case  insensitive,  numbers   str2); as  numbers strncasecomp() Compares  two  strings  (not  case  sensitive)  and  allows  you  to   specify  how  many  characters  to  compare strspn() Compares  a  string  against  characters  represented  by  a  mask strcspn() Compares  a  string  that  contains  characters  not  in  the  mask   The strcmp() Function (Case Sensitive) The strcmp() function is most often used to compare two strings. Format int strcmp ( string str1, string str2 )   Example: $number = strcmp( "apples", "oranges"); The strcmp() function uses a lexicographical comparison algorithm to compare two strings, meaning it 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 in the ASCII table; that is, 65 is less than 97. The strcmp() function returns a number less than 0 if the first string is less than second string, a number greater than 0 if the first string is greater than the second string, and 0 if they are equal. The strcmp() function is case sensitive meaning that “Dan” and “dan” are not the same. If you want to ignore the case of the letters, use the strcasecmp() function discussed next. See Example 6.13 to see how the strcmp() function works and its output in Figure 6.12. Example 6.13. Code  View:     The strcmp() Function Comparing Strings
  12. 1 print "strcmp( '$string1', '$string2' ) outputs " . strcmp( $string1, $string2 ); 2 print "\nstrcmp( '$string2', '$string2' ) outputs " . strcmp( $string2,$string2 ); 3 print "\nstrcmp( '$string2', '$string1' ) outputs " . strcmp( $string2, $string1 ); 4 print "\nstrcmp( 'dan', 'Dan' ) outputs " . strcmp( 'dan', 'Dan'); print "\nstrcmp( 'Dan', 'dan' ) outputs " . strcmp( 'Dan', 'dan'); ?> Explanation 1 Dan  is  lexiographically  smaller  then  Daniel,  resulting  in  a  negative  number. 2 Daniel  and  Daniel  are  identical,  thus  we  get  zero  as  the  result  of  comparison. 3 Daniel  is  larger  then  Dan,  resulting  in  a  positive  number. 4 The  d  in  dan  is  greater  than  the  D  in  Dan,  a  positive  number.  See  Figure  6.12. Figure 6.12. The strcmp() function. Output from Example 6.13.   Please purchase PDF Split-Merge on to remove this watermark.
  13. The strcasecmp() Function (Case Insensitive) The strcasecmp() function works like the strcmp() function, but ignores the case of characters in strings; that is, an uppercase “A” and a lowercase “a” are treated as equals when comparing characters. The strcasecmp() function returns a number less than 0 if the first string is less than the second string, a number greater than 0 if the first string is greater than the second string, and 0 if they are equal. Example 6.14 demonstrates how the function works. Format int strcasecmp ( string str1, string str2 )   Example: $number=strcasecmp("apples", "APples"); // Case-insensitive comparison Example 6.14. Explanation 1 Two  string  variables  are  assigned  the  same  string,  only  differing  in  case. 2 The  strcasecmp()  function  ignores  the  difference  in  case  and  compares  the  characters.   The  strings  are  equal.  Remember  that  if  the  returned  value  == 0,  the  strings  are  equal.   See  Figure  6.13.   Figure 6.13. Case-insensitive string comparison.     Please purchase PDF Split-Merge on to remove this watermark.
  14. The strncasecmp() Function (Limits Character Length) This strncasecmp() function is similar to strcasecmp() in that it also ignores the case of characters when doing the comparison, but in addition, it lets you specify the (upper limit of the) number of characters (length) from each string to be used in the comparison. The strncasecmp() function returns a number less than 0 if the first string is less than the second string, a number greater than 0 if the first string is greater than the 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 Explanation 1 Two  string  variables  are  assigned  the  same  string,  differing  only  in  case. 2 The  strncasecmp()  function  ignores  the  difference  in  case  and  compares  only   the  first  5  characters.  The  third  argument,  5,  specifies  how  many  characters   you  want  to  compare  starting  at  the  beginning  of  the  string.  The  strings  are   equal.  See  Figure  6.14. Figure 6.14. The strncasecmp() function.   Please purchase PDF Split-Merge on to remove this watermark.
  15. The strnatcmp() Function (Natural Order Comparison) If you compare numeric strings, the expression '2' > '100' will evaluate to true because in the first position 2 is greater than 1 when using the ASCII collating sequence. The other character positions are irrelevant because the first string only has one character. The string comparison functions we have seen so far always cast their arguments to strings before doing the comparison. The strnatcmp() function takes into consideration strings that contain numbers. This function compares characters in two strings using the ASCII collating sequence, but if there are any numbers within the string they are compared in natural order; that is, as numbers the way we think of numbers, where 100 is greater than 2. This is true even if the numbers occur in the middle of the string. Thus 'January 2' will evaluate to less than 'January 10', whereas in a normal string comparison it would be greater since 2 is greater than 1. The strnatcasecmp() function is just like the strnatcmp() function except that it is not case insensitive when comparing strings. Format int strnatcmp ( string str1, string str2 )   Example: // Returns 1 -- string 2 > string 1 echo strnatcmp('January 2, 2006', 'January 10, 2006'); // Returns -1 -- string 1 > string 2 echo strcmp( 'January 2, 2006', 'January 10, 2006' ); The strspn() Function (Using a Mask for Comparison) The strspn() function compares two strings and returns the number of characters that are contained in the initial part of the first string that match a set of characters provided in the second string, called the mask. For example, if you want to check that a password contains both digits and letters or if a zip code consists of only numbers, this function can be used to check that specified characters are included in the string. The two optional arguments allow you define where you want to start looking for the characters in the string and the length of the string to compare. Example 6.16 demonstrates how to use the strspn() function. Format int strspn ( string str1, string str2 [, int start [, int length]] )   Example: $year = "1953 was a very good year!"; $mask="0123456789" $count=strspn($year,$mask,0,4); // The string must start with 4 digits Example 6.16. The strspn() Function Finding the Length of a String by a Mask
  16. Explanation 1 $mask  consists  of  a  string  of  numbers  that  will  serve  as  the  mask. 2 The  variable,  $zip,  contains  numbers. 3 The  strspn()  function  returns  the  number  of  characters  in  $zip  that  match   the  characters  in  the  mask.  The  strspn()  function  should  return  a  count  of  5,   because  there  are  5  numbers  in  $zip  and  they  are  all  found  in  the  mask   variable. 4 This  line  checks  if  the  value  of  $count  is  equal  to  the  number  of  characters  in   $zip,  the  string  length,  and  if  so,  prints  “The  zip  code  consists  of  5  numbers.” The strcspn() Function (Comparison Not Matching a Mask) The strcspn() function is just like the strspn() function, but finds length of initial segment not matching the mask; that is, it returns the length of the initial segment of the first string not containing any of the characters in the second string. The strcspn() function accepts two optional integer parameters that can be used to define the start position and the length of the string being compared. Format int strcspn ( string str1, string str2 [, int start [, int length]] )   Example: $filename = "test3"; $length=strcspn("$filename", "1234567890", 0, 4); // Returns 4; first 4 characters should not be numbers 6.2.7. Finding Similarities in Strings The string comparison functions previously discussed perform alphanumeric string comparisons, but what if we want to see if one string sounds or is pronounced like another or how and where the text differs in two strings? PHP provides a set of functions to find similarities or differences in strings. These functions might be useful for programs that check spelling, perform database searches, or any advanced text processing. The soundex() and metaphone() Functions (Phonic Similarity) Phonic similarity bases its comparison on whether or not two strings are homophones, that is, they sound alike. Words such as “genes” and “jeans” or “morning” and “mourning” are homophones. The soundex() and metaphone() functions take a string as an argument, and return a key. Soundex keys are short alphanumeric representations of a word’s English pronounciation that can be used to compare the sound in strings. If the keys are the same, then the words sound the same in English. After testing different words, you will see that these functions base their comparison on American English 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 6.15. Format string soundex ( string str ) string metaphone ( string str [, int phones] )   Example: $key1=soundex("bored"); $key2=soundex("board"); if ( $key1 == $key2 ){ echo "The strings sound alike";} Please purchase PDF Split-Merge on to remove this watermark.
  17. Example 6.17. Code  View:   Words that Sound the Same Explanation 1 The  two  variables,  $string1  and  $string2,  are  assigned  strings  whose  values  sound  the   same,  called  homophones. 2 The  keys  produced  by  the  soundex()  function  are  shown  in  Figure  6.15.  They  are  four   character  strings,  which  can  be  compared. 3 If  the  keys  are  the  same,  the  words  are  homophones. 4 Two  more  homophones  are  assigned  to  $sound1  and  $sound2,  respectively. 5 The  keys  returned  from  the  metaphone()  function  are  more  precise  in  dealing  with   English  pronunciation.   Please purchase PDF Split-Merge on to remove this watermark.
  18. Figure 6.15. Homophones—words that sound the same. The similar_text() and levenshtein() Functions (Textual Similarity) PHP provides two functions to test the similarity between the text in two strings. They are the similar_text() and the levenshtein() functions. The similar_text() function calculates the similarity of two strings and returns the number of characters that are the same, allowing for additions, subtraction, and repetition. It also takes an optional third parameter, containing a value that represents the percentage of similarity between the strings. Example 6.18 demonstrates how the similar_text() function is used. Format int similar_text ( string first, string second [, float percent] )   Example: $number_same = similar_text($a, $b, $percent); Example 6.18. Text that is Similar Please purchase PDF Split-Merge on to remove this watermark.
  19. Explanation 1,   Two  similar  strings  are  assigned  to  variables. 2 3,   The  similar_text()  function  returns  the  number  of  characters  that  are  the  same  and  a   4 value  indicating  the  percentage  of  the  alikeness  of  the  two  strings.  They  are  87%   similar.  See  Figure  6.16.   Figure 6.16. The similar_text() function.     The levenshtein() function is used to find the Levenshtein[2] distance (also called the edit distance) between two strings (strings cannot be longer than 255 characters). What’s that? Suppose you have two strings and you want to know how you could edit one of the strings to make it just like the other string. (If you have ever used the UNIX diff command, it will give you this kind of information.) The Levenshtein distance is defined as the fewest number of insertions, substitutions, and deletions required to transform one string into another string. (The function is not case sensitive.) The greater the Levenshtein distance, the more different the strings are. If the distance is 0, the strings are the same. (For full discussion see Example 6.19 demonstrates how to use the levenshtein() function. [2] Levenshtein distance is named after the Russian scientist Vladimir Levenshtein, who wrote the algorithm in 1965. Format int levenshtein ( string str1, string str2 [, int cost_ins [, int cost_rep, int cost_del]] )   Example: $diff = levenshtein($string1, $string2); $diff = levenshtein($string1, $string2, 100, 5, 1); Example 6.19. Text that is Similar
  20. print "First string: $string1\n"; print "Second string: $string2\n"; 2 $distance=levenshtein("$string1", "$string2"); print "It would take $distance changes to transform string1 into string2."; ?> Explanation 1 Two  strings  are  assigned.  They  have  some  characters  in  common.  What  would  it  take  to   transform  the  first  string  into  the  second? 2 The  levenshtein()  function  will  figure  out  the  minimum  number  of  insertions,   deletions,  or  substitutions  it  would  take  to  transform  the  first  string  into  the  second.  In   this  example,  the  first  change  would  be  I.  It  would  take  two  substitutions  to  change  it  to   He.  The  next  change  would  be  to  replace  the  e  in  funeral  with  a  space  (three  changes  so   far),  then  to  add  the  ly  in  rally,  two  more  changes,  making  a  total  of  five.  See  Figure   6.17  for  output.   Figure 6.17. The levenshtein() function.     The levenshtein() function includes the first two strings and three additional parameters that define the cost of insert, substitute, and delete operations. This allows you to specify how you want scores weighted with numeric values. Otherwise, all scores are given equal weight. The weight or cost indicates what steps should be taken to make the strings similar; that is, should insertions or deletions be made to transform the string? 6.2.8. 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, 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 to remove this watermark.
Đồng bộ tài khoản