1 / 32

Objectives

Chapter 3 Manipulating Strings PHP Programming with MySQL 2 nd Edition M odified by Anita Philipp – Spring 2011. Objectives. In this chapter, you will: Construct text strings Work with single strings Work with multiple strings and parse strings Compare strings Use regular expressions.

bobdavidson
Download Presentation

Objectives

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 3Manipulating StringsPHP Programming with MySQL2nd EditionModified by Anita Philipp –Spring 2011

  2. Objectives In this chapter, you will: • Construct text strings • Work with single strings • Work with multiple strings and parse strings • Compare strings • Use regular expressions PHP Programming with MySQL, 2nd Edition

  3. Constructing Text Strings • A text string contains zero or more characters surrounded by double or single quotation marks • Text can be used as literals or be assigned to variables echo"<p>PHP literal text string</p>"; $TextString =‘<p>PHP text string</p>’;echo $TextString Strings must begin and end with matching quotation marks PHP Programming with MySQL, 2nd Edition

  4. Constructing Text Strings (continued) Alternate single and double quotes $Quote='<p>"Et tu, Brute!"</p>'; echo $Quote; PHP Programming with MySQL, 2nd Edition

  5. Working with String Operators Concatenation operator (.) combines two strings and assigns the new value to a variable $City = “Paris”; $Country = “France”; $Place = “<p>”. $City .“, “. $Country .“</p>”; echo $Place; PHP Programming with MySQL, 2nd Edition

  6. Working with String Operators • Combine strings using the concatenation assignment operator (.=) $Destination = "<p>Paris"; $Destination .= ” is in France.</p>"; echo $Destination; PHP Programming with MySQL, 2nd Edition

  7. Escape Characters • Escape Character • Character that follows it has a special purpose • Escape character is the backslash (\) echo '<p>This code\'s going to work</p>'; • Not needed if single/double quotes are alternated echo "<p>This code's going to work.</p>"; PHP Programming with MySQL, 2nd Edition

  8. Escape Sequence • Escape character combined with one or more other characters PHP Programming with MySQL, 2nd Edition

  9. Escape Sequences $Speaker = "Julius Caesar”; echo "<p>\"Et tu, Brute!\" exclaimed $Speaker.</p>"; PHP Programming with MySQL, 2nd Edition

  10. Simple / Complex String Syntax • Complex string syntax • Variables are within curly braces inside of a string • $Vegetable = "carrot"; • echo "<p>Do you have any {$Vegetable}s?</p>"; Simple string syntax Include variable name inside a string with double quotes $Vegetable = "broccoli"; echo "<p>Do you have any $Vegetable?</p>”; PHP Programming with MySQL, 2nd Edition

  11. String Functions: strlen() • strlen() • returns the number of characters in a string • Escape sequences, such as \n, are counted as one character $TextString = 'Cody\'s Car'; $TextLength = strlen($TextString); echo "<p>$TextString contains $TextLength characters.</p>"; PHP Programming with MySQL, 2nd Edition

  12. String Functions: str_word_count() • str_word_count() • Pass a literal string or a string variable • Returns the number of words in a string $String = 'Cody\'s Car'; $Words = str_word_count($String); echo "<p>$String contains $Words words.</p>"; PHP Programming with MySQL, 2nd Edition

  13. String Functions: Change Case • strtoupper()converts all letters to uppercase • strtolower() converts all letters to lowercase • ucfirst()ensures the first character is uppercase • lcfirst()ensures the first character is lowercase (PHP 5.3+) • ucwords()ensures all words begin with uppercase $String = "look at me”; echo"<p>"; echo strtoupper($String)."<br/>"; echo strtolower($String)."<br/>"; echo ucfirst($String)."<br/>"; echo lcfirst($String)."<br/>"; echo ucwords($String); echo "</p>"; PHP Programming with MySQL, 2nd Edition

  14. String Functions: Encode/Decode • htmlspecialchars() • converts special chars to HTML entities • html_specialcharacters_decode() • converts HTML entities into their equivalent chars $new = htmlspecialchars("Encode: \” <hr/>"); echo ”<p>$new</p>"; $str = 'Decode: &quot; &lt;br/&gt;'; echo ”<p>”.htmlspecialchars_decode($str).”</p>”; PHP Programming with MySQL, 2nd Edition

  15. String Functions: Encode/Decode • htmlspecialchars()conversions: • &&amp; • “ &quot;1. • ’&#039;2. • <&lt; • >&gt; • ENT_NOQUOTES - disables conversion of “ • ENT_QUOTES - enables conversion of ‘ PHP Programming with MySQL, 2nd Edition

  16. String Functions: Encode/Decode • md5() • Creates a one-way hash* • Utilizes strong encryption algorithm • Message-Digest Algorithm • No equivalent decode function – useful for storing passwords • $Password = "str0ngpwd";$HashResult = md5($Password);echo $HashResult; *one-way hash is a fixed-length string based on the entered text, from which it is nearly impossible to determine the original text PHP Programming with MySQL, 2nd Edition

  17. String Functions: trim() $String = " spaces ”; echo "<p>trim() |” . trim($String) . "|</p>"; echo"<p>ltrim() |” . ltrim($String) . "|</p>"; echo "<p>rtrim() |” . rtrim($String) . "|</p>"; • trim()removes leading and trailing spaces • ltrim()removes only leading spaces • rtrim()removes only the trailing spaces PHP Programming with MySQL, 2nd Edition

  18. String Functions: substr() • substr() • Returns substring using parameters of start and length • Start Parameter • Positive - start position from beginning (begins with 0) • Negative - start position from end • 0 – start position is the beginning • Length Parameter • Default – to end of string • Positive – length from start parameter • Negative – number of characters omitted from the end of the string • Greater than remaining characters – remaining string returned PHP Programming with MySQL, 2nd Edition

  19. String Functions: substr() $ExampleString = "woodworking project”; echo "1 ". substr($ExampleString,4) . "<br />”; echo "2 ". substr($ExampleString,4,7). "<br />”; echo "3 ". substr($ExampleString,0,8). "<br />”; echo "4 ". substr($ExampleString,4,-8)."<br />”; echo "5 ". substr($ExampleString,-7) . "<br />”; echo "6 ". substr($ExampleString,-15,4). "<br />”; echo "7 ". substr($ExampleString,-15,-8). "<br />"; PHP Programming with MySQL, 2nd Edition

  20. String Functions: Parsing • Parsing • Dividing a string into substrings / tokens • String search and extraction functions • Return a numeric position in a text string …or… • Return a character or substring…or… • Return FALSE if not found PHP Programming with MySQL, 2nd Edition

  21. String Functions: strpos() $String = “Sara.A.Student@email.occc.edu”; $Result = strpos("$String”,”@"); echo "Result: $Result <br />"; $Result = strpos("$String”,”A"); echo "CaseSensitive: $Result <br />”; $Result = stripos("$String”,”A"); echo "Case Insensitive: $Result <br />" • strpos() • case-sensitive search • returns the position of first occurrence of string • returns FALSE if not found • stripos() • case-insensitive search • returns the position of first occurrence of string • returns FALSE if not found • Two arguments: string to be searched, characters for which to search PHP Programming with MySQL, 2nd Edition

  22. String Functions: strchr() $String="Red Rover"; echo "Beginning: ”.strchr($String,"R").”<br />"; echo "End: ”.strrchr($String,"R”).”<br />"; echo "Beginning: ”.strchr($String,"r").”<br />"; echo "End: ”.strrchr($String, "r").”<br />"; • strchr(), strrchr() • Arguments: string, search character • return a substring from the specified characters to the end of the string • strchr()search from beginning • strrchr()search from end PHP Programming with MySQL, 2nd Edition

  23. String Functions: strreplace() • str_replace(), str_ireplace() • Arguments: search string, replacement string, string • str_replace()– case sensitive • str_ireplace()– case insensitive $Email = "Mr.President@whitehouse.gov"; $Search = "mr.president"; $NewEmail = str_replace($Search,"Mr.Vice.President”,$Email); echo $NewEmail."<br/>"; $NewEmail = str_ireplace($Search,"Mr.Vice.President”,$Email); echo $NewEmail; PHP Programming with MySQL, 2nd Edition

  24. String Functions: strtok() • strtok()divide a string into tokens • Arguments: String, separator • Returns entire string when • An empty string is specified as the second argument • Does not contain any of the separators $Presidents = "Washington|Jefferson|Madison"; $MrPresident = strtok($Presidents, ”|"); while ($MrPresident != NULL) { echo "$MrPresident<br />"; $MrPresident = strtok(";"); } PHP Programming with MySQL, 2nd Edition

  25. String Functions: str_split(), explode() • str_split(), explode()split a string into an indexed array • str_split() • Arguments: string, length of each element • explode() • Arguments: separators, string • When separators not found, entire string is assigned to $ArrayName[0] • Does not separate a string at each character that is included in the separator argument • Evaluates the characters in the separator argument as a substring • Empty string as the separator argument then function returns a Boolean value of FALSE PHP Programming with MySQL, 2nd Edition

  26. String Functions: str_split(), explode() $States = "Oklahoma;Texas"; $StatesArray = explode(";", $States); foreach ($StatesArray as $StateCode) { echo "$StateCode<br />"; } $States = "OKTX"; $StatesArray = str_split($States, 2); foreach ($StatesArray as $StateCode) { echo "$StateCode<br />"; } PHP Programming with MySQL, 2nd Edition

  27. String Functions: implode() • implode() • combines an array’s elements into a single string • separated by specified characters • Arguments: separators, array $DaysArray = array("FR","SA","SU"); $Weekend = implode(",",$DaysArray); echo "$Weekend"; PHP Programming with MySQL, 2nd Edition

  28. String Functions: Comparisons • Comparison operators use ASCII codes • Lowercase letters • 97 (“a”) to 122 (“z”) • Uppercase letters • 65 (“A”) to 90 (“Z”) $First = "A"; $Second = "a"; if ($First > $Second ) echo "<p>$First is greater than $Second./p>"; else echo "<p>$Second is greater than $First.</p>"; PHP Programming with MySQL, 2nd Edition

  29. String Functions: Comparisons • strcasecmp(), strcmp() • Arguments: String 1, String 2 • Compare based on ASCII Value • Positive number – first is greater • Negative number - second is greater • strcasecmp() – case-insensitive • strcmp() – case-sensitive • strncmp(), strncasecmp() • Arguments: String 1, String 2, Number of chars to compare • Similar strings – longer is greater $First = "Birth”; $Second = "Birthday"; echo ”Result strcmp: ". strcmp($First, $Second)."<br/>”; echo ”Result strncmp: ". strncmp($First, $Second, 5); PHP Programming with MySQL, 2nd Edition

  30. String Functions: Similar Text • similar_text(), levenshtein() • Determine similarity between two strings • Arguments: two strings • similar_text() • returns the number of common characters • levenshtein() • returns the number of characters needing change to make strings the same $First = "Smith"; $Second = "Smyth"; $Same = similar_text($First, $Second); $Change = levenshtein($First, $Second); echo"<p>$First|$Second have $Same chars in common.</p>"; echo"<p>$First|$Second have $Change chars to change.</p>"; PHP Programming with MySQL, 2nd Edition

  31. String Functions: Sound Comparisons • soundex(), metaphone() • Can use to determine whether strings are pronounced similarly • Return a value representing how words sound • soundex() • Returns 4 character alphanumeric representing pronunciations (English) • metaphone() • Returns code representing word’s approximate sound (English) $First = "son"; $Second = "sun"; $Soundex1=soundex($First); $Soundex2=soundex($Second); $MPhone1=metaphone($First); $MPhone2=metaphone($Second); echo "For son and sun:<br/>"; echo "soundex codes: $Soundex1 and $Soundex2<br/>"; echo "metaphone codes: $MPhone1 and $MPhone2"; PHP Programming with MySQL, 2nd Edition

  32. THE END

More Related