Manipulating Strings. 2 Topics Manipulate strings Manipulate strings Parse strings Parse strings...

36
Manipulating Manipulating Strings Strings
  • date post

    21-Dec-2015
  • Category

    Documents

  • view

    268
  • download

    3

Transcript of Manipulating Strings. 2 Topics Manipulate strings Manipulate strings Parse strings Parse strings...

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

Manipulating StringsManipulating Strings

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

22

TopicsTopics

Manipulate stringsManipulate strings Parse stringsParse strings Compare stringsCompare strings Handle form Handle form

submissionssubmissions

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

33

Constructing Text StringsConstructing Text Strings A text string contains zero or more A text string contains zero or more

characters characters A string may be surrounded by double or A string may be surrounded by double or

single quotation markssingle quotation marks Text strings can be used as literal values Text strings can be used as literal values

or assigned to a variableor assigned to a variableecho "<p>Dr. Livingstone, I presume?</p>";echo "<p>Dr. Livingstone, I presume?</p>";

$Explorer = "Henry M. Stanley";$Explorer = "Henry M. Stanley";

echo $Explorer;echo $Explorer;

PHP has no “character” data typePHP has no “character” data type

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

44

Constructing Text Strings Constructing Text Strings

Double quotation marks may be Double quotation marks may be embedded in single quotation marksembedded in single quotation marks

Single quotation marks may be Single quotation marks may be embedded in double quotation marksembedded in double quotation marks$phrase = “You’re the greatest.”;$phrase = “You’re the greatest.”;

$greet = ‘I said, “Hello!”’;$greet = ‘I said, “Hello!”’;

echo $greet;echo $greet;

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

55

mail()mail() Function Function

Used to send an email from a PHP scriptUsed to send an email from a PHP script SyntaxSyntax mail(mail(recipient(s)recipient(s), , subjectsubject, , message message [[,, headers]) headers])

• Headers might include To, From, CC, BCC, DateHeaders might include To, From, CC, BCC, Date The The mail()mail() function returns a boolean function returns a boolean

• true if a message was delivered successfully true if a message was delivered successfully

• false if it was notfalse if it was not

Contact your ISP for the name of your SMTP ServerContact your ISP for the name of your SMTP Server

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

66

<?php$from = “[email protected]";$to = "[email protected]";$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";

elseecho "Error sending message";

?>

Sending mailSending mail

SMTP Server name

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

77

Combining StringsCombining Strings

Concatenation operatorConcatenation operator (.) (.)

$Destination = "Paris";$Destination = "Paris";

$Location = "France";$Location = "France";

$Destination = $Destination . “ is in “ . $Location";$Destination = $Destination . “ is in “ . $Location";

echo $Destination;echo $Destination;

Concatenation assignment Concatenation assignment operatoroperator (.=) (.=)

$Destination = "Paris ";$Destination = "Paris ";

$Destination .= "is in France";$Destination .= "is in France";

echo $Destination;echo $Destination;

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

88

Escape CharactersEscape Characters

Tells the compiler or interpreter that Tells the compiler or interpreter that following character has a special purposefollowing 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!';echo 'You\'re the best!';

• Not needed before an apostrophe if the text string Not needed before an apostrophe if the text string is surrounded with double quotesis surrounded with double quotes

echo “You're the best!”;echo “You're the best!”;

No backslash needed

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

99

Escape SequencesEscape Sequences

echo “File location: C:\\My Documents\\CSci116\\”;echo “File location: C:\\My Documents\\CSci116\\”;

$name = "Fred";$name = "Fred";

echo '"Hi!," said $name.'; echo '"Hi!," said $name.'; "Hi!," said $name."Hi!," said $name.

echo "\"Hi!,\" said $name."; echo "\"Hi!,\" said $name."; "Hi!," said Fred."Hi!," said Fred.

echo '"Hi!,"' . " said $name."; echo '"Hi!,"' . " said $name."; "Hi!," said Fred."Hi!," said Fred.

echo '"Hi!,"', " said $name."; echo '"Hi!,"', " said $name."; "Hi!," said Fred."Hi!," said Fred.

this won’t work

solutions

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

1010

Simple and Complex String Simple and Complex String SyntaxSyntax

Simple string syntaxSimple string syntax

$veg1 = "broccoli";$veg1 = "broccoli";

$veg2 = "carrot";$veg2 = "carrot";

echo "Do you have any $veg1?";echo "Do you have any $veg1?";

echo "Do you have any $veg2s?";echo "Do you have any $veg2s?";

Complex string syntaxComplex string syntax

echo "Do you have any {$veg2}s?";echo "Do you have any {$veg2}s?";

this works

this doesn’t

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

1111

String Counting FunctionsString Counting Functions

strlen()strlen() returns the total number of returns the total number of characters in a stringcharacters in a string• strlen(“Howdy!”)strlen(“Howdy!”) 6 6

str_word_count()str_word_count() returns the number returns the number of words in a stringof words in a string• str_word_count(“Have a nice day”)str_word_count(“Have a nice day”) 4 4

substr_count()substr_count() returns the number of returns the number of occurrences of a substring in a stringoccurrences of a substring in a string• substr_count(“Yabba Dabba Doo”,substr_count(“Yabba Dabba Doo”,

“abba”)“abba”) 2 2

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

1212

strpos()strpos() Function Function

Performs a case-sensitive search and Performs a case-sensitive search and returns the position of the first occurrence returns the position of the first occurrence of one string in another stringof one string in another string• Returns Returns falsefalse if the search string is not found if the search string is not found

Two argumentsTwo arguments• The string you want to search The string you want to search • The characters you want to look forThe characters you want to look for

ExampleExample• strpos(“Hello”, “lo”); strpos(“Hello”, “lo”); 3 3

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

1313

strchr()strchr() and and strrchr()strrchr()

Return a substring from the specified Return a substring from the specified characters to the end of the stringcharacters to the end of the string

• strchr()strchr() starts searching at the beginning of starts searching at the beginning of a stringa string

strchr(“Hello there”, “e”);strchr(“Hello there”, “e”); ello there ello there

• strrchr()strrchr() starts searching at the starts searching at the end of a stringend of a string

• strrchr(“Hello there”, “e”);strrchr(“Hello there”, “e”); e e

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

1414

substr()substr() Function Function

Extracts characters from the beginning or Extracts characters from the beginning or middle of a stringmiddle of a string

ExampleExample$Email = "[email protected]";$Email = "[email protected]";$NameEnd = $NameEnd = strpos($Email, "@")strpos($Email, "@");;echo echo substr($Email, 0, $NameEnd)substr($Email, 0, $NameEnd);;

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

1515

str_replace()str_replace() and and str_ireplace()str_ireplace()

str_replace()str_replace() and and str_ireplace()str_ireplace() accept three arguments:accept three arguments:• The string you want to replace The string you want to replace • The new replacement stringThe new replacement string• The string you are searchingThe string you are searching

$Email = "[email protected]";$Email = "[email protected]";

$NewEmail = $NewEmail = str_replace("president", "vice.president", $Email)str_replace("president", "vice.president", $Email);;

echo $NewEmail; // prints '[email protected]'echo $NewEmail; // prints '[email protected]'

str_ireplace()str_ireplace() is case- is case-insensitiveinsensitive

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

1616

The The strtok()strtok() Function Function

Use Use strtok()strtok() to break a string into smaller to break a string into smaller strings, called strings, called tokenstokens

Syntax Syntax $variable $variable = strtok(= strtok(string, separatorsstring, separators););

strtok()strtok() returns the entire string if: returns the entire string if:• An empty string is specified as the second argument of An empty string is specified as the second argument of

the the strtok()strtok() function function • The string does not contain any of the separators The string does not contain any of the separators

specifiedspecified

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

1717

strtok()strtok() Function Function

$cartoons = "Donald Duck;Mickey Mouse;Goofy";$cartoons = "Donald Duck;Mickey Mouse;Goofy";

$name = strtok($cartoons, ";");$name = strtok($cartoons, ";");

while ($name != null)while ($name != null)

{{

echo "$name<br />";echo "$name<br />";

$name = strtok(";");$name = strtok(";");

}}

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

1818

$cartoons = "Donald Duck;Mickey Mouse;Goofy";$cartoons = "Donald Duck;Mickey Mouse;Goofy";

$name = strtok($cartoons, "; ");$name = strtok($cartoons, "; ");

while ($name != null)while ($name != null)

{{

echo "$name<br />";echo "$name<br />";

$name = strtok("; ");$name = strtok("; ");

}}

strtok()strtok() Function (continued) Function (continued)

Two separators – a semicolon and

a space

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

1919

Converting Strings to ArraysConverting Strings to Arrays

str_split() str_split() and and explode()explode() functions functions split a string into an indexed arraysplit a string into an indexed array

Make it easier to work with string tokensMake it easier to work with string tokens str_split()str_split() uses a uses a lengthlength argument to argument to

represent the number of characters to represent the number of characters to assign to each array elementassign to each array element

$$array array = str_split(= str_split(stringstring[, [, lengthlength]);]); explode()explode() splits a string at a specified splits a string at a specified

separatorseparator$$array array = explode(= explode(separatorsseparators, string);, string);

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

2020

str_split()str_split()

$months = "JanFebMarApr";$months = "JanFebMarApr";

$month_array = str_split($months, 3);$month_array = str_split($months, 3);

foreach($month_array as $month)foreach($month_array as $month)

echo "$month<br />";echo "$month<br />";

*Note that each element must have the same length*Note that each element must have the same length

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

2121

explode()explode()

$cartoons = "Donald Duck;Mickey Mouse;Goofy";$cartoons = "Donald Duck;Mickey Mouse;Goofy";

$cartoon_array = explode(";", $cartoons);$cartoon_array = explode(";", $cartoons);

foreach($cartoon_array as $cartoon)foreach($cartoon_array as $cartoon)

echo "$cartoon<br />";echo "$cartoon<br />";

If the string does not contain If the string does not contain the specified separators, the the specified separators, the entire string is assigned to the entire string is assigned to the first element of the arrayfirst element of the array

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

2222

implode()implode() Combines an array’s elements into a single Combines an array’s elements into a single

string, separated by specified charactersstring, separated by specified characters$v$variable ariable = implode(= implode(separatorsseparators, , arrayarray););

$PresidentsArray = array("George W. Bush", "William Clinton", $PresidentsArray = array("George W. Bush", "William Clinton",

"George H.W. Bush", "Ronald Reagan", "Jimmy Carter");"George H.W. Bush", "Ronald Reagan", "Jimmy Carter");

$Presidents = $Presidents = implode(", ", $PresidentsArray)implode(", ", $PresidentsArray);;

echo $Presidents;echo $Presidents;

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

2323

Comparing StringsComparing Strings

$cartoon1 = “Minnie Mouse";$cartoon1 = “Minnie Mouse";

$cartoon2 = “Mickey Mouse";$cartoon2 = “Mickey Mouse";

if ($cartoon1 == $cartoon2)if ($cartoon1 == $cartoon2)

echo "<p>Same cartoon.</p>";echo "<p>Same cartoon.</p>";

elseelse

echo "<p>Different cartoons.</p>";echo "<p>Different cartoons.</p>";

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

2424

Comparing Strings (continued)Comparing Strings (continued)

$cartoon1 = "Pluto";$cartoon1 = "Pluto";

$cartoon2 = "pluto";$cartoon2 = "pluto";

if ($cartoon1 < $cartoon2)if ($cartoon1 < $cartoon2)

echo "$cartoon1 comes echo "$cartoon1 comes before $cartoon2";before $cartoon2";

elseelse

echo "$cartoon2 comes echo "$cartoon2 comes before $cartoon1";before $cartoon1";

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

2525

ASCIIASCII

Numeric representations of English charactersNumeric representations of English characters ASCII values range from 0 to 256ASCII values range from 0 to 256 Lowercase letters are represented by the values Lowercase letters are represented by the values

97 (“a”) to 122 (“z”) 97 (“a”) to 122 (“z”) Uppercase letters are represented by the values Uppercase letters are represented by the values

65 (“A”) to 90 (“Z”)65 (“A”) to 90 (“Z”) Lowercase letters have higher values than Lowercase letters have higher values than

uppercase letters, so they are evaluated as being uppercase letters, so they are evaluated as being “greater” than uppercase letters“greater” than uppercase letters

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

2626

String Comparison FunctionsString Comparison Functions The The strcasecmp()strcasecmp() function performs a function performs a

case-insensitive comparison of stringscase-insensitive comparison of strings• strcasecmp(“DAISY", “daisy")strcasecmp(“DAISY", “daisy") true true

The The strcmp()strcmp() function performs a function performs a case-sensitive comparison of stringscase-sensitive comparison of strings• strcmp(“DAISY", “daisy")strcmp(“DAISY", “daisy") false false

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

2727

Determining the Similarity of Determining the Similarity of Two StringsTwo Strings

The The similar_text()similar_text() and and levenshtein()levenshtein() functions are used to determine the functions are used to determine the similarity between two stringssimilarity between two strings

• similar_text()similar_text() returns the number of returns the number of characters that two strings have in commoncharacters that two strings have in common

• levenshtein()levenshtein() returns the number of returns the number of characters you need to change for two strings characters you need to change for two strings to be the sameto be the same

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

2828

similar_text()similar_text() and and levenshtein()levenshtein()

$FirstName = “Mickey";$FirstName = “Mickey";

$SecondName = “Minney";$SecondName = “Minney";

echo "<p>The names \"$FirstName\“ and \"$SecondName\“ have “ . echo "<p>The names \"$FirstName\“ and \"$SecondName\“ have “ .

similar_text($FirstName, $SecondName) similar_text($FirstName, $SecondName) . “ characters in . “ characters in

common.</p>";common.</p>";

echo "<p>You must change “ . echo "<p>You must change “ . levenshtein($FirstName, $SecondName)levenshtein($FirstName, $SecondName)

. “ character(s) to make the names the same.</p>";. “ character(s) to make the names the same.</p>";

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

2929

Determining if Words Are Determining if Words Are Pronounced SimilarlyPronounced Similarly

The The soundex()soundex() and and metaphone()metaphone() functions functions determine whether two strings are determine whether two strings are pronounced similarlypronounced similarly

The The soundex()soundex() function returns a value function returns a value representing a name’s phonetic equivalentrepresenting a name’s phonetic equivalent

The The metaphone()metaphone() function returns a code function returns a code representing an English word’s soundrepresenting an English word’s sound

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

3030

metaphone()metaphone()

$name1 = “Harry";$name1 = “Harry";$name2 = “hairy";$name2 = “hairy";if (metaphone($name1) == metaphone($name2))if (metaphone($name1) == metaphone($name2))

echo ("The names sound the same");echo ("The names sound the same");elseelse

echo ("The names do not sound the same");echo ("The names do not sound the same");

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

3131

Handling Form SubmissionsHandling Form Submissions

A A query string query string is a set of name=value pairs is a set of name=value pairs appended to a target URLappended to a target URL

Form data is submitted in name=value pairsForm data is submitted in name=value pairs GETGET method appends a question mark (?) and method appends a question mark (?) and

query string to the URL of any forms that are query string to the URL of any forms that are submitted with the submitted with the GETGET method method

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

3232

Handling Form SubmissionsHandling Form Submissions

A user can bypass JavaScript form A user can bypass JavaScript form validation on the clientvalidation on the client• If If getget is used, they can type in a URL is used, they can type in a URL• If If postpost is used, they can construct a is used, they can construct a

transmission using HTTP headerstransmission using HTTP headers Always use PHP code to validate Always use PHP code to validate

submitted datasubmitted data

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

3333

Validating Submitted DataValidating Submitted Data

Use Use isset()isset() or or empty()empty() functions to functions to ensure that a variable contains a valueensure that a variable contains a value• if (isset($_GET[‘amount’]))if (isset($_GET[‘amount’]))• if (!empty($_GET[‘amount’]))if (!empty($_GET[‘amount’]))

Use Use is_numeric()is_numeric() to test whether a to test whether a variable contains a numeric stringvariable contains a numeric string• if (is_numeric($_GET[‘amount’]))if (is_numeric($_GET[‘amount’]))

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

3434

ExampleExample<body>

<form action="creditCard.php" method="post">Enter your credit card number:<br /><input type="text" name="ccnumber" size="20"><br /><input type="submit" value="Validate"><br />

</form><?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.";

elseecho "Your credit card number is not valid.";

}?>

</body>

create the form

check to see if a value was entered

strip out dashesand spaces

check to see ifwhat’s left isnumeric

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

3535

SummarySummary

The concatenation operator (.) and the The concatenation operator (.) and the concatenation assignment operator (.=) can be concatenation assignment operator (.=) can be used to combine stringsused to combine strings

An escape character tells the compiler or An escape character tells the compiler or interpreter that the character following the interpreter that the character following the escape character has a special purposeescape character has a special purpose

strlen()strlen() returns the total number of characters returns the total number of characters in a stringin a string

str_replace(),str_replace(), str_ireplace()str_ireplace(), and , and substr_replace()substr_replace() functions replace text in functions replace text in stringsstrings

strtok()strtok() breaks a string into smaller strings, breaks a string into smaller strings, called tokenscalled tokens

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

3636

Summary (continued)Summary (continued)

str_split()str_split() and and explode()explode() split a string into an split a string into an indexed arrayindexed array

The The implode()implode() function combines an array’s function combines an array’s elements into a single stringelements into a single string

strcasecmp()strcasecmp() performs a case-insensitive string performs a case-insensitive string comparison strings, and comparison strings, and strcmp()strcmp() performs a performs a case-sensitive comparisoncase-sensitive comparison

similar_text()similar_text() and and levenshtein()levenshtein() determine determine the similarity of two stringsthe similarity of two strings

soundex()soundex() and and metaphone()metaphone() determine whether determine whether two strings are pronounced similarlytwo strings are pronounced similarly