Presentation is loading. Please wait.

Presentation is loading. Please wait.

Manipulating Strings. 2 Topics Manipulate strings Manipulate strings Parse strings Parse strings Compare strings Compare strings Handle form submissions.

Similar presentations


Presentation on theme: "Manipulating Strings. 2 Topics Manipulate strings Manipulate strings Parse strings Parse strings Compare strings Compare strings Handle form submissions."— Presentation transcript:

1 Manipulating Strings

2 2 Topics Manipulate strings Manipulate strings Parse strings Parse strings Compare strings Compare strings Handle form submissions Handle form submissions

3 3 Constructing Text Strings A text string contains zero or more characters A text string contains zero or more characters A string may be surrounded by double or single quotation marks A string may be surrounded by double or single quotation marks Text strings can be used as literal values or assigned to a variable Text strings can be used as literal values or assigned to a variable echo " Dr. Livingstone, I presume? "; $Explorer = "Henry M. Stanley"; echo $Explorer; PHP has no “character” data type PHP has no “character” data type

4 4 Constructing Text Strings Double quotation marks may be embedded in single quotation marks Double quotation marks may be embedded in single quotation marks Single quotation marks may be embedded in double quotation marks Single quotation marks may be embedded in double quotation marks $phrase = “You’re the greatest.”; $greet = ‘I said, “Hello!”’; echo $greet;

5 5 mail() Function Used to send an email from a PHP script Used to send an email from a PHP script Syntax Syntax mail(recipient(s), subject, message [, headers]) mail(recipient(s), subject, message [, headers]) Headers might include To, From, CC, BCC, DateHeaders might include To, From, CC, BCC, Date The mail() function returns a boolean The mail() function returns a boolean true if a message was delivered successfullytrue if a message was delivered successfully false if it was notfalse if it was not Contact your ISP for the name of your SMTP Server Contact your ISP for the name of your SMTP Server

6 6 <?php $from = “tinajo@comcast.net"; $to = "tostrand@highline.edu"; $subject = "Hello"; $message = "This is a message"; $headers = "From: $from"; ini_set("sendmail_from", $from); ini_set("SMTP", "smtp.comcast.net"); $success = mail($to, $subject, $message, $headers); if ($success) echo "Message sent successfully"; else echo "Error sending message"; ?> Sending mail SMTP Server name

7 7 Combining Strings Concatenation operator (.) Concatenation operator (.) $Destination = "Paris"; $Location = "France"; $Destination = $Destination. “ is in “. $Location"; echo $Destination; Concatenation assignment operator (.=) Concatenation assignment operator (.=) $Destination = "Paris "; $Destination.= "is in France"; echo $Destination;

8 8 Escape Characters Tells the compiler or interpreter that following character has a special purpose Tells the compiler or interpreter that following character has a special purpose In PHP, the escape character is a backslash \ In PHP, the escape character is a backslash \ echo 'You\'re the best!'; Not needed before an apostrophe if the text string is surrounded with double quotesNot needed before an apostrophe if the text string is surrounded with double quotes echo “You're the best!”; No backslash needed

9 9 Escape Sequences echo “File location: C:\\My Documents\\CSci116\\”; $name = "Fred"; echo '"Hi!," said $name.';  "Hi!," said $name. echo "\"Hi!,\" said $name.";  "Hi!," said Fred. echo '"Hi!,"'. " said $name.";  "Hi!," said Fred. echo '"Hi!,"', " said $name.";  "Hi!," said Fred. this won’t work solutions

10 10 Simple and Complex String Syntax Simple string syntax Simple string syntax $veg1 = "broccoli"; $veg1 = "broccoli"; $veg2 = "carrot"; echo "Do you have any $veg1?"; echo "Do you have any $veg2s?"; Complex string syntax Complex string syntax echo "Do you have any {$veg2}s?"; this works this doesn’t

11 11 String Counting Functions strlen() returns the total number of characters in a string strlen() returns the total number of characters in a string strlen(“Howdy!”)  6strlen(“Howdy!”)  6 str_word_count() returns the number of words in a string str_word_count() returns the number of words in a string str_word_count(“Have a nice day”)  4str_word_count(“Have a nice day”)  4 substr_count() returns the number of occurrences of a substring in a string substr_count() returns the number of occurrences of a substring in a string substr_count(“Yabba Dabba Doo”, “abba”)  2substr_count(“Yabba Dabba Doo”, “abba”)  2

12 12 strpos() Function Performs a case-sensitive search and returns the position of the first occurrence of one string in another string Performs a case-sensitive search and returns the position of the first occurrence of one string in another string Returns false if the search string is not foundReturns false if the search string is not found Two arguments Two arguments The string you want to searchThe string you want to search The characters you want to look forThe characters you want to look for Example Example strpos(“Hello”, “lo”);  3strpos(“Hello”, “lo”);  3

13 13 strchr() and strrchr() Return a substring from the specified characters to the end of the string Return a substring from the specified characters to the end of the string strchr() starts searching at the beginning of a stringstrchr() starts searching at the beginning of a string strchr(“Hello there”, “e”);  ello there strchr(“Hello there”, “e”);  ello there strrchr() starts searching at the end of a stringstrrchr() starts searching at the end of a string strrchr(“Hello there”, “e”);  estrrchr(“Hello there”, “e”);  e

14 14 substr() Function Extracts characters from the beginning or middle of a string Extracts characters from the beginning or middle of a string Example Example $Email = "president@whitehouse.gov"; $NameEnd = strpos($Email, "@"); echo substr($Email, 0, $NameEnd);

15 15 str_replace() and str_ireplace() str_replace() and str_ireplace() accept three arguments: str_replace() and str_ireplace() accept three arguments: The string you want to replaceThe string you want to replace The new replacement stringThe new replacement string The string you are searchingThe string you are searching $Email = "president@whitehouse.gov"; $NewEmail = str_replace("president", "vice.president", $Email); echo $NewEmail; // prints 'vice.president@whitehouse.gov' str_ireplace() is case-insensitive str_ireplace() is case-insensitive

16 16 The strtok() Function Use strtok() to break a string into smaller strings, called tokens Use strtok() to break a string into smaller strings, called tokens Syntax Syntax $variable = strtok(string, separators); $variable = strtok(string, separators); strtok() returns the entire string if: strtok() returns the entire string if: An empty string is specified as the second argument of the strtok() functionAn empty string is specified as the second argument of the strtok() function The string does not contain any of the separators specifiedThe string does not contain any of the separators specified

17 17 strtok() Function $cartoons = "Donald Duck;Mickey Mouse;Goofy"; $name = strtok($cartoons, ";"); while ($name != null) { echo "$name "; $name = strtok(";"); }

18 18 $cartoons = "Donald Duck;Mickey Mouse;Goofy"; $name = strtok($cartoons, "; "); while ($name != null) { echo "$name "; $name = strtok("; "); } strtok() Function (continued) Two separators – a semicolon and a space

19 19 Converting Strings to Arrays str_split() and explode() functions split a string into an indexed array str_split() and explode() functions split a string into an indexed array Make it easier to work with string tokens Make it easier to work with string tokens str_split() uses a length argument to represent the number of characters to assign to each array element str_split() uses a length argument to represent the number of characters to assign to each array element $array = str_split(string[, length]); $array = str_split(string[, length]); explode() splits a string at a specified separator explode() splits a string at a specified separator $array = explode(separators, string);

20 20 str_split() $months = "JanFebMarApr"; $month_array = str_split($months, 3); foreach($month_array as $month) echo "$month "; *Note that each element must have the same length

21 21 explode() $cartoons = "Donald Duck;Mickey Mouse;Goofy"; $cartoon_array = explode(";", $cartoons); foreach($cartoon_array as $cartoon) echo "$cartoon "; If the string does not contain the specified separators, the entire string is assigned to the first element of the array If the string does not contain the specified separators, the entire string is assigned to the first element of the array

22 22 implode() Combines an array’s elements into a single string, separated by specified characters Combines an array’s elements into a single string, separated by specified characters $variable = implode(separators, array); $PresidentsArray = array("George W. Bush", "William Clinton", "George H.W. Bush", "Ronald Reagan", "Jimmy Carter"); $Presidents = implode(", ", $PresidentsArray); echo $Presidents;

23 23 Comparing Strings $cartoon1 = “Minnie Mouse"; $cartoon2 = “Mickey Mouse"; if ($cartoon1 == $cartoon2) echo " Same cartoon. "; else echo " Different cartoons. ";

24 24 Comparing Strings (continued) $cartoon1 = "Pluto"; $cartoon2 = "pluto"; if ($cartoon1 < $cartoon2) echo "$cartoon1 comes before $cartoon2"; else echo "$cartoon2 comes before $cartoon1";

25 25 ASCII Numeric representations of English characters Numeric representations of English characters ASCII values range from 0 to 256 ASCII values range from 0 to 256 Lowercase letters are represented by the values 97 (“a”) to 122 (“z”) Lowercase letters are represented by the values 97 (“a”) to 122 (“z”) Uppercase letters are represented by the values 65 (“A”) to 90 (“Z”) Uppercase letters are represented by the values 65 (“A”) to 90 (“Z”) Lowercase letters have higher values than uppercase letters, so they are evaluated as being “greater” than uppercase letters Lowercase letters have higher values than uppercase letters, so they are evaluated as being “greater” than uppercase letters

26 26 String Comparison Functions The strcasecmp() function performs a case-insensitive comparison of strings The strcasecmp() function performs a case-insensitive comparison of strings strcasecmp(“DAISY", “daisy")  truestrcasecmp(“DAISY", “daisy")  true The strcmp() function performs a case-sensitive comparison of strings The strcmp() function performs a case-sensitive comparison of strings strcmp(“DAISY", “daisy")  falsestrcmp(“DAISY", “daisy")  false

27 27 Determining the Similarity of Two Strings The similar_text() and levenshtein() functions are used to determine the similarity between two strings The similar_text() and levenshtein() functions are used to determine the similarity between two strings similar_text() returns the number of characters that two strings have in commonsimilar_text() returns the number of characters that two strings have in common levenshtein() returns the number of characters you need to change for two strings to be the samelevenshtein() returns the number of characters you need to change for two strings to be the same

28 28 similar_text() and levenshtein() $FirstName = “Mickey"; $SecondName = “Minney"; echo " The names \"$FirstName\“ and \"$SecondName\“ have “. similar_text($FirstName, $SecondName). “ characters in common.</p>"; echo " You must change “. levenshtein($FirstName, $SecondName). “ character(s) to make the names the same. ";

29 29 Determining if Words Are Pronounced Similarly The soundex() and metaphone() functions determine whether two strings are pronounced similarly The soundex() and metaphone() functions determine whether two strings are pronounced similarly The soundex() function returns a value representing a name’s phonetic equivalent The soundex() function returns a value representing a name’s phonetic equivalent The metaphone() function returns a code representing an English word’s sound The metaphone() function returns a code representing an English word’s sound

30 30 metaphone() $name1 = “Harry"; $name2 = “hairy"; if (metaphone($name1) == metaphone($name2)) echo ("The names sound the same"); else echo ("The names do not sound the same");

31 31 Handling Form Submissions A query string is a set of name=value pairs appended to a target URL A query string is a set of name=value pairs appended to a target URL Form data is submitted in name=value pairs Form data is submitted in name=value pairs GET method appends a question mark (?) and query string to the URL of any forms that are submitted with the GET method GET method appends a question mark (?) and query string to the URL of any forms that are submitted with the GET method

32 32 Handling Form Submissions A user can bypass JavaScript form validation on the client A user can bypass JavaScript form validation on the client If get is used, they can type in a URLIf get is used, they can type in a URL If post is used, they can construct a transmission using HTTP headersIf post is used, they can construct a transmission using HTTP headers Always use PHP code to validate submitted data Always use PHP code to validate submitted data

33 33 Validating Submitted Data Use isset() or empty() functions to ensure that a variable contains a value Use isset() or empty() functions to ensure that a variable contains a value if (isset($_GET[‘amount’]))if (isset($_GET[‘amount’])) if (!empty($_GET[‘amount’]))if (!empty($_GET[‘amount’])) Use is_numeric() to test whether a variable contains a numeric string Use is_numeric() to test whether a variable contains a numeric string if (is_numeric($_GET[‘amount’]))if (is_numeric($_GET[‘amount’]))

34 34 Example Enter your credit card number: <?php if(isset($_POST["ccnumber"])) { $num = $_POST["ccnumber"]; $num = str_replace("-", "", $num); $num = str_replace(" ", "", $num); if(is_numeric($num)) echo "Your credit card number is $num."; else echo "Your credit card number is not valid."; } ?> create the form check to see if a value was entered strip out dashes and spaces check to see if what’s left is numeric

35 35 Summary The concatenation operator (.) and the concatenation assignment operator (.=) can be used to combine strings The concatenation operator (.) and the concatenation assignment operator (.=) can be used to combine strings An escape character tells the compiler or interpreter that the character following the escape character has a special purpose An escape character tells the compiler or interpreter that the character following the escape character has a special purpose strlen() returns the total number of characters in a string strlen() returns the total number of characters in a string str_replace(), str_ireplace(), and substr_replace() functions replace text in strings str_replace(), str_ireplace(), and substr_replace() functions replace text in strings strtok() breaks a string into smaller strings, called tokens strtok() breaks a string into smaller strings, called tokens

36 36 Summary (continued) str_split() and explode() split a string into an indexed array str_split() and explode() split a string into an indexed array The implode() function combines an array’s elements into a single string The implode() function combines an array’s elements into a single string strcasecmp() performs a case-insensitive string comparison strings, and strcmp() performs a case-sensitive comparison strcasecmp() performs a case-insensitive string comparison strings, and strcmp() performs a case-sensitive comparison similar_text() and levenshtein() determine the similarity of two strings similar_text() and levenshtein() determine the similarity of two strings soundex() and metaphone() determine whether two strings are pronounced similarly soundex() and metaphone() determine whether two strings are pronounced similarly


Download ppt "Manipulating Strings. 2 Topics Manipulate strings Manipulate strings Parse strings Parse strings Compare strings Compare strings Handle form submissions."

Similar presentations


Ads by Google