Presentation is loading. Please wait.

Presentation is loading. Please wait.

Faculty of Sciences and Social Sciences HOPE PHP – Working with Files and Strings Stewart Blakeway FML 213

Similar presentations


Presentation on theme: "Faculty of Sciences and Social Sciences HOPE PHP – Working with Files and Strings Stewart Blakeway FML 213"— Presentation transcript:

1 www.hope.ac.uk Faculty of Sciences and Social Sciences HOPE PHP – Working with Files and Strings Stewart Blakeway FML 213 blakews@hope.ac.uk

2 www.hope.ac.uk Faculty of Sciences and Social Sciences HOPE 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 www.hope.ac.uk Faculty of Sciences and Social Sciences HOPE 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 www.hope.ac.uk Faculty of Sciences and Social Sciences HOPE 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 www.hope.ac.uk Faculty of Sciences and Social Sciences HOPE 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 www.hope.ac.uk Faculty of Sciences and Social Sciences HOPE printf() <?php $num1=20.5; printf ("The original number is: %f ",$num1); printf ("Now it is: %d ",$num1); printf ("Now it is: %b ",$num1); echo ($num1); ?>

7 www.hope.ac.uk Faculty of Sciences and Social Sciences HOPE printf() %dDecimal (base 10) %bBinary (base 2) %cInteger as ASCII equivalent %fFloat %oOctal (base 8) %sString %xHexadecimal (base 16)

8 www.hope.ac.uk Faculty of Sciences and Social Sciences HOPE 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 www.hope.ac.uk Faculty of Sciences and Social Sciences HOPE Leading Zeros printf(“%010d”,36); will print “ 0000000036 ”

10 www.hope.ac.uk Faculty of Sciences and Social Sciences HOPE Other characters Other characters can be used instead of zeros they must be followed by a single quotation mark printf(“%’*20d”,36); ******************36

11 www.hope.ac.uk Faculty of Sciences and Social Sciences HOPE Leading Spaces You have to use the tag! Multiple white spaces are ignored by the web browser. You can force white space to be displayed by using the pre tag.

12 www.hope.ac.uk Faculty of Sciences and Social Sciences HOPE Using <?php printf(" Hello World!"); ?> Will print the leading spaces. pre is the html tag that tells the browser to print as it appears!

13 www.hope.ac.uk Faculty of Sciences and Social Sciences HOPE Question What will be printed to screen? <?php printf(" Hello World!"); ?> Parse error: parse error, unexpected '<' in C:\Program Files\Apache Group\Apache2\htdocs\pre.PHP on line 9

14 www.hope.ac.uk Faculty of Sciences and Social Sciences HOPE How about now? <?php echo " "; printf(" Hello World!"); echo " "; ?>

15 www.hope.ac.uk Faculty of Sciences and Social Sciences HOPE Specifying a string length You can specify a length of a string using the same technique seen in padding. <?php echo " "; printf("%20s ","Apples"); printf("%20s ","Bananas"); printf("%20s ","Pears"); echo " "; ?>

16 www.hope.ac.uk Faculty of Sciences and Social Sciences HOPE Specifying the string length By default spaces are printed first You can change this behaviour by using a - <?php echo " "; printf("%-20s\n","Apples"); printf("%-20s\n","Bananas"); printf("%-20s\n","Pears"); echo " "; ?>

17 www.hope.ac.uk Faculty of Sciences and Social Sciences HOPE String Length $file = fopen("student_list.txt","r"); while (!feof($file)) { echo " "; printf ("%100s ",fgets($file)); echo " "; }

18 www.hope.ac.uk Faculty of Sciences and Social Sciences HOPE Arrays and Strings A string is an array of characters $test= “ Hello World! ” echo ($test[6]); W

19 www.hope.ac.uk Faculty of Sciences and Social Sciences HOPE 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 www.hope.ac.uk Faculty of Sciences and Social Sciences HOPE What is echoed out? $studentID=("05001221222"); if (strlen ($studentID) > 10) { echo ("Student Number is too many characters!"); } else { echo ("Student Number accepted"); }

21 www.hope.ac.uk Faculty of Sciences and Social Sciences HOPE 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 www.hope.ac.uk Faculty of Sciences and Social Sciences HOPE 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 www.hope.ac.uk Faculty of Sciences and Social Sciences HOPE Final 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"); } stristr()stristr() – Not case sensitive

24 www.hope.ac.uk Faculty of Sciences and Social Sciences HOPE 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! "); echo ("At position". strpos($userString,"bomb")); } else { echo ("Text contains no keywords posing a threat to the nation"); }

25 www.hope.ac.uk Faculty of Sciences and Social Sciences HOPE 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). " "); }

26 www.hope.ac.uk Faculty of Sciences and Social Sciences HOPE 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 www.hope.ac.uk Faculty of Sciences and Social Sciences HOPE 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 www.hope.ac.uk Faculty of Sciences and Social Sciences HOPE 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 www.hope.ac.uk Faculty of Sciences and Social Sciences HOPE 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 www.hope.ac.uk Faculty of Sciences and Social Sciences HOPE 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 www.hope.ac.uk Faculty of Sciences and Social Sciences HOPE A further refinement $userEmail=("blakews@hope.ac.uk"); if (substr($userEmail, -2,2) == "uk") { echo ("UK customers pay £5 postage "); 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 www.hope.ac.uk Faculty of Sciences and Social Sciences HOPE 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 www.hope.ac.uk Faculty of Sciences and Social Sciences HOPE What is echoed out? $userString=("Hello everybody, it is a lovely day"); $delim = (" "); $word = (strtok($userString, $delim)); echo $word;

34 www.hope.ac.uk Faculty of Sciences and Social Sciences HOPE What about now? $userString=("Hello everybody, it is a lovely day"); $delim = (" "); $word = (strtok($userString,$delim)); $count=0; while (is_string($word)) { echo ($word." "); $count++; $word = (strtok($delim)); } echo ($count. “words in the string”);

35 www.hope.ac.uk Faculty of Sciences and Social Sciences HOPE 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 www.hope.ac.uk Faculty of Sciences and Social Sciences HOPE strip_tags() Strip tags is very useful for stripping html tags from a string $mytext = ( “ Hello World! ” ); echo strip_tags ($mytext);

37 www.hope.ac.uk Faculty of Sciences and Social Sciences HOPE 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 www.hope.ac.uk Faculty of Sciences and Social Sciences HOPE Converting Case PHP provides 4 functions that manipulate the case of a string – strtoupper(); – strtolower(); – ucwords(); – ucfirst();

39 www.hope.ac.uk Faculty of Sciences and Social Sciences HOPE Example $mytext “heLLo wORLd!” strtoupper($mytext); // HELLO WORLD! strtolower($mytext); // hello world! ucwords($mytext); // Hello World! ucfirst($mytext); // Hello world!

40 www.hope.ac.uk Faculty of Sciences and Social Sciences HOPE 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 $myarray with two indexes. $myarray[0] = “Hello”; $myarray[1] = “World”;

41 www.hope.ac.uk Faculty of Sciences and Social Sciences HOPE 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 www.hope.ac.uk Faculty of Sciences and Social Sciences HOPE 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 function getUsersText() { echo (" <form id='form1' name='form1' method='post' action='$_SERVER[PHP_SELF]'> Enter some text <textarea name='usersText' id='usersText' cols='45' rows='5'> <input type='submit' name='checkSpelling' id='checkSpelling' value='Check Spelling' /> "); } 1. Get users text

43 www.hope.ac.uk Faculty of Sciences and Social Sciences HOPE 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 www.hope.ac.uk Faculty of Sciences and Social Sciences HOPE 3. Check Spelling Create a function called checkSpelling – the function will receive two arguments $userText and $word – use the explode function to split the $userText into an array called $userWord – for each word in the array $userWord check against each word in the array $word – if a match is found, copy the word to a variable called $correctUsersText without any formatting, else copy with bold formatting – return $correctUsersText

45 www.hope.ac.uk Faculty of Sciences and Social Sciences HOPE 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.= " ". $currentUserWord. " "; } $found = False; } return $correctUsersText; }

46 www.hope.ac.uk Faculty of Sciences and Social Sciences HOPE 4. Output the spelling mistakes Create a function called display – accept one argument – echo the argument function display ($txt) { echo $txt; }

47 www.hope.ac.uk Faculty of Sciences and Social Sciences HOPE 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 www.hope.ac.uk Faculty of Sciences and Social Sciences HOPE Spot the mistakes $mystring = “Last updated 2001” $mystring = substr_replace (mystring, “2007” -4, 4);

49 www.hope.ac.uk Faculty of Sciences and Social Sciences HOPE 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 www.hope.ac.uk Faculty of Sciences and Social Sciences HOPE Summary Slide Strings printf() function Padding and Printf() tag Specifying a string length Arrays and Strings Finding the length of a string Reporting the position of the found criteria

51 www.hope.ac.uk Faculty of Sciences and Social Sciences HOPE Summary Slide (cont.) Extracting specific text from a string Splitting a string into new strings Stripping HTML tags from strings Replacing a portion of the string Converting the Case of a string Breaking strings into arrays

52 www.hope.ac.uk Faculty of Sciences and Social Sciences HOPE Any Questions? Next Week – connecting to a SQL Server – creating a Database – selecting a Database – adding to a Database


Download ppt "Faculty of Sciences and Social Sciences HOPE PHP – Working with Files and Strings Stewart Blakeway FML 213"

Similar presentations


Ads by Google