1 / 52

PHP – Working with Files and Strings

PHP – Working with Files and Strings. Stewart Blakeway FML 213 blakews@hope.ac.uk. What will we cover. How to format strings Determining a string length How to find a string within a string Breaking down a string into component parts Removing white spaces from a string. Why?.

Download Presentation

PHP – Working with Files and Strings

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. PHP – Working with Files and Strings Stewart Blakeway FML 213 blakews@hope.ac.uk

  2. What will we cover • How to format strings • Determining a string length • How to find a string within a string • Breaking down a string into component parts • Removing white spaces from a string

  3. Why? • As part of your assessment marking criteria you are marked on how you present information • If you can format your text you will score higher on that aspect of the mark sheet

  4. Strings • What is a string? • Two characters or more, a word, a sentence, a paragraph and so-forth • Until now we have only passed strings to functions or echoed them out. Sometimes you will want to manipulate the text within a string

  5. printf() function • printf() is based on the function originally written in C • It works like the echo function with the advantage of automatically converting an integer or float • It also has the advantage of accepting parameters from the end of the statement to be included anywhere in the string

  6. printf() <?php $num1=20.5; printf ("The original number is: %f<br>",$num1); printf ("Now it is: %d <br>",$num1); printf ("Now it is: %b <br>",$num1); echo ($num1); ?>

  7. printf() %d Decimal (base 10) %b Binary (base 2) %c Integer as ASCII equivalent %f Float %o Octal (base 8) %s String %x Hexadecimal (base 16)

  8. Padding and Printf() • by default all leading zeros and spaces will be omitted from a string • You can force leading zeros or spaces to be displayed by using the padding specifier • %0

  9. Leading Zeros • printf(“%010d”,36); • will print “0000000036”

  10. Other characters • Other characters can be used instead of zeros • they must be followed by a single quotation mark printf(“%’*20d”,36); ******************36

  11. Leading Spaces • You have to use the <pre> tag! • Multiple white spaces are ignored by the web browser. • You can force white space to be displayed by using the pre tag.

  12. Using <pre> <pre> <?php printf(" Hello World!"); ?> </pre> • Will print the leading spaces. pre is the html tag that tells the browser to print as it appears!

  13. Question What will be printed to screen? <?php <pre> printf(" Hello World!"); </pre> ?> Parse error: parse error, unexpected '<' in C:\Program Files\Apache Group\Apache2\htdocs\pre.PHP on line 9

  14. How about now? <?php echo "<pre>"; printf(" Hello World!"); echo "</pre>"; ?>

  15. Specifying a string length • You can specify a length of a string using the same technique seen in padding. <?php echo "<pre>"; printf("%20s<br />","Apples"); printf("%20s<br />","Bananas"); printf("%20s<br />","Pears"); echo "</pre>"; ?>

  16. Specifying the string length • By default spaces are printed first • You can change this behaviour by using a - <?php echo "<pre>"; printf("%-20s\n","Apples"); printf("%-20s\n","Bananas"); printf("%-20s\n","Pears"); echo "</pre>"; ?>

  17. String Length $file = fopen("student_list.txt","r"); while (!feof($file)) { echo "<pre>"; printf ("%100s<br />",fgets($file)); echo "</pre>"; }

  18. Arrays and Strings • A string is an array of characters $test=“Hello World!” echo ($test[6]); W

  19. Finding the length of a string • strlen() is a function that will return the length of a string $slength = strlen(“Hello World!”); echo ($slength); • This could be used for validation

  20. What is echoed out? $studentID=("05001221222"); if (strlen ($studentID) > 10) { echo ("Student Number is too many characters!"); } else { echo ("Student Number accepted"); }

  21. Examining the contents of a string • strstr() is a function that searches the string depending on a criteria you specify! $studentID=("05001221222"); if (strstr ($studentID,"0500")) { echo ("Student registered in 2005"); } else { echo ("Student did not register in 2005"); }

  22. Another example $userString=("I heard Simon knows how to make bombs!"); if (strstr ($userString,"bomb")) { echo ("Warning! Text contains something about bombs!"); } else { echo ("Text contains no keywords posing a threat to the nation"); }

  23. Final example stristr() – Not case sensitive $userString=("I heard Simon knows how to make Bombs!"); if (strstr ($userString,"bomb")) { echo ("Warning! Text contains something about bombs!"); } else { echo ("Text contains no keywords posing a threat to the nation"); }

  24. Reporting the position of the found criteria • strpos() will report the position of the criteria found $userString=("I heard Simon knows how to make bombs!"); if (strstr ($userString,"bomb")) { echo ("Warning! Text contains something about bombs! <br>"); echo ("At position" . strpos($userString,"bomb")); } else { echo ("Text contains no keywords posing a threat to the nation"); }

  25. Lets put it all together to create something useful! $naughtyWord = array ("bomb","detonate","detonator","tnt","explosion"); $userString=("I heard Simon knows how to make bombs! He uses tnt and a detonator to create a huge explosion!"); foreach ($naughtyWord as $currentWord) { if (strstr ($userString,$currentWord)) { echo ("Warning! Text contains naughty word: ".$currentWord); echo (" at position" . strpos($userString,$currentWord) . "<br>"); } }

  26. Extracting specific text from a string • substr() will allow you to copy certain characters or a group of characters from a string! • They must be adjacent • You can start from the beginning or the end of the string

  27. substr() $userString=("I heard Simon knows how to make bombs! He uses tnt and a detonator to create a huge explosion!"); echo (substr($userString, 8));

  28. substr() $userString=("I heard Simon knows how to make bombs! He uses tnt and a detonator to create a huge explosion!"); echo (substr($userString, 8,5));

  29. From the end of the string $userString=("I heard Simon knows how to make bombs! He uses tnt and a detonator to create a huge explosion!"); echo (substr($userString, -10,10));

  30. How could this be useful? $userEmail=("blakews@hope.ac.uk"); if (substr($userEmail, -2,2) == "uk") { echo ("UK customers pay £5 postage"); } else { echo ("You are not based in the UK, postage is £15"); }

  31. A further refinement $userEmail=("blakews@hope.ac.uk"); if (substr($userEmail, -2,2) == "uk") { echo ("UK customers pay £5 postage<br>"); if (substr($userEmail, -6) == ".ac.uk") { echo ("You work in education, you save a further 10%"); } } else { echo ("You are not based in the UK, postage is £15"); }

  32. Splitting a string into new strings • Excel or Access for example will save a file as a text file using delimiters to separate each column • Sometimes you will want to split a string into a new string depending on delimiters • This is achieved by using the strtok() function

  33. What is echoed out? $userString=("Hello everybody, it is a lovely day"); $delim = (" "); $word = (strtok($userString, $delim)); echo $word;

  34. What about now? $userString=("Hello everybody, it is a lovely day"); $delim = (" "); $word = (strtok($userString,$delim)); $count=0; while (is_string($word)) { echo ($word."<br />"); $count++; $word = (strtok($delim)); } echo ($count. “words in the string”);

  35. Sometimes you will want to remove white space from strings • trim () Deletes all white spaces from the right and left of the string • ltrim () Deletes all white spaces from the left of the string • rtrim () Deletes all white spaces from the right of the string $string = trim ($string);

  36. strip_tags() • Strip tags is very useful for stripping html tags from a string $mytext = (“<h1>Hello World!</h1>”); echo strip_tags ($mytext);

  37. Replacing a portion of the string • The substr_replace() function works like the substr() except it allows you to replace the section of the string $mystring = “Last updated 2001”; $mystring = substr_replace ($mystring, “2007”, -4, 4);

  38. Converting Case • PHP provides 4 functions that manipulate the case of a string • strtoupper(); • strtolower(); • ucwords(); • ucfirst();

  39. Example $mytext “heLLowORLd!” strtoupper($mytext); // HELLO WORLD! strtolower($mytext); // hello world! ucwords($mytext); // Hello World! ucfirst($mytext); // Hello world!

  40. Breaking strings into arrays • PHP offers a function that will take a string of text and put each word into an array with a separate index $myarray= explode(“ ”, “Hello World!”); • Produces an array called $myarraywith two indexes. • $myarray[0] = “Hello”; • $myarray[1] = “World”;

  41. Working Example • The objective is to allow the user to check their spelling • Get the users text • Compare each word with a valid word • If the word does not match a valid word, highlight the word dict.lst ======== a -> z

  42. 1. Get users text function getUsersText() { echo (" <form id='form1' name='form1' method='post' action='$_SERVER[PHP_SELF]'> <p>Enter some text<br /> <textarea name='usersText' id='usersText' cols='45' rows='5'></textarea> </p> <p> <input type='submit' name='checkSpelling' id='checkSpelling' value='Check Spelling' /> </p></form> "); } • How do we get user input from the users? • Create a function called getUsersText • Create a form • action=‘$_SERVER[PHP_SELF]’ • Create a textarea called usersText

  43. 2. Read in a dictionary • Create a function called buildDictionary • open a file for reading called dict.lst • while not end of the file read each line and put into an array called $word[] • return the array function buildDictionary () { $dictionary = fopen("dict.lst","r"); while (!feof($dictionary)) { $word[] = fgets($dictionary); } return $word; }

  44. 3. Check Spelling • Create a function called checkSpelling • the function will receive two arguments • $userTextand $word • use the explode function to split the $userText into an array called $userWord • for each word in the array $userWordcheck against each word in the array $word • if a match is found, copy the word to a variable called $correctUsersTextwithout any formatting, else copy with bold formatting • return $correctUsersText

  45. 3. Check spelling function checkSpelling($usersText, $word) { $usersWord = explode(" ",$usersText); foreach ($usersWord as $currentUserWord) { foreach ($word as $currentDictionaryWord) { if (trim($currentDictionaryWord) == trim($currentUserWord)) { $correctUsersText .= $currentUserWord . " "; $found = True; break; } } if (!$found) { $correctUsersText .= "<b>" . $currentUserWord . "</b> "; } $found = False; } return $correctUsersText; }

  46. 4. Output the spelling mistakes • Create a function called display • accept one argument • echo the argument function display ($txt) { echo $txt; }

  47. Putting it all together if (!isset($_POST['usersText'])) { getUsersText(); } else { $words = buildDictionary(); $correctUsersText = checkSpelling($_POST['usersText'],$words); display ($correctUsersText); } You should now be creating functions that mean something to you and perform a specific task. Sometimes you will want to pass values to the function so that is has something to work with Sometimes you will want an answer from a function

  48. Spot the mistakes $mystring = “Last updated 2001” $mystring = substr_replace (mystring, “2007” -4, 4);

  49. Spot the mistakes $userEmail=(blakews@hope.ac.uk); if (substr($userEmail, -2,2) == "uk" echo ("UK customers pay £5 postage"); else echo ("You are not based in the UK, postage is £15");

  50. Summary Slide • Strings • printf() function • Padding and Printf() • <pre> </pre> tag • Specifying a string length • Arrays and Strings • Finding the length of a string • Reporting the position of the found criteria

More Related