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

Slides:



Advertisements
Similar presentations
Computer Science & Engineering 2111 Text Functions 1CSE 2111 Lecture-Text Functions.
Advertisements

Faculty of Sciences and Social Sciences HOPE PHP Flow Control Website Development Stewart Blakeway FML
Faculty of Sciences and Social Sciences HOPE PHP & MySQL Stewart Blakeway FML 213
Faculty of Sciences and Social Sciences HOPE Functions in PHP Stewart Blakeway FML
Faculty of Sciences and Social Sciences HOPE PHP – Working with Input Stewart Blakeway FML 213
Chapter 9: Arrays and Strings
IS 1181 IS 118 Introduction to Development Tools Chapter 4 String Manipulation and Regular Expressions.
Operations & Strings CSCI 116 Web Programming I. 2 Arithmetic Operators Arithmetic operators are used to perform mathematical calculations.
PHP Server-side Programming. PHP  PHP stands for PHP: Hypertext Preprocessor  PHP is interpreted  PHP code is embedded into HTML code  interpreter.
PHP Overview CS PHP PHP = PHP: Hypertext Preprocessor Server-side scripting language that may be embedded into HTML One goal is to get PHP files.
PHP Tutorials 02 Olarik Surinta Management Information System Faculty of Informatics.
PHP : Hypertext Preprocessor
Open Source Server Side Scripting ECA 236 Open Source Server Side Scripting PHP Form Handling.
Reading Data in Web Pages tMyn1 Reading Data in Web Pages A very common application of PHP is to have an HTML form gather information from a website's.
Strings and Arrays. String Is a sequence of characters. Example: “hello”, “how are you?”, “123”,and are all valid string values.
Lecture 6 – Form processing (Part 1) SFDV3011 – Advanced Web Development 1.
Strings IDIA 618 Spring 2013 Bridget M. Blodgett.
INTERNET APPLICATION DEVELOPMENT For More visit:
PHP Workshop ‹#› Data Manipulation & Regex. PHP Workshop ‹#› What..? Often in PHP we have to get data from files, or maybe through forms from a user.
NMED 3850 A Advanced Online Design January 26, 2010 V. Mahadevan.
Nael Alian Introduction to PHP
Mr. Justin “JET” Turner CSCI 3000 – Fall 2015 CRN Section A – TR 9:30-10:45 CRN – Section B – TR 5:30-6:45.
XP 1 Microsoft Word 2002 Tutorial 1 – Creating a Document.
Chapter 8 Cookies And Security JavaScript, Third Edition.
Chapter 3 Processing and Interactive Input. 2 Assignment  The general syntax for an assignment statement is variable = operand; The operand to the right.
Faculty of Sciences and Social Sciences HOPE JavaScript Advanced Stewart Blakeway FML
Web-Based Database Programming with PHP. Dept. of Computing Science, University of Aberdeen2 In this lecture you will learn PHP Basics PHP functions –To.
Web Database Programming Week 3 PHP (2). Functions Group related statements together to serve “a” specific purpose –Avoid duplicated code –Easy maintenance.
13/2/12 Lecture 6. Functions 2 types: – Built in functions – Custom defined functions Functions minimize the amount of repetition of code. function consists.
PHP: A RRAYS, S TRINGS, AND F ILES CSCI 297 Scripting Languages - Day Three.
1Computer Sciences Department Princess Nourah bint Abdulrahman University.
Open Source Server Side Scripting ECA 236 Open Source Server Side Scripting PHP & MySQL.
What is PHP? PHP stands for PHP: Hypertext Preprocessor PHP is a server-side scripting language, like ASP PHP scripts are executed on the server PHP supports.
Algorithms  Problem: Write pseudocode for a program that keeps asking the user to input integers until the user enters zero, and then determines and outputs.
CS161 Topic #16 1 Today in CS161 Lecture #16 Prepare for the Final Reviewing all Topics this term Variables If Statements Loops (do while, while, for)
Introducing Python CS 4320, SPRING Lexical Structure Two aspects of Python syntax may be challenging to Java programmers Indenting ◦Indenting is.
Using Text Files in Excel File I/O Methods. Working With Text Files A file can be accessed in any of three ways: –Sequential access: By far the most common.
Representing Strings and String I/O. Introduction A string is a sequence of characters and is treated as a single data item. A string constant, also termed.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
CSC 1010 Programming for All Lecture 3 Useful Python Elements for Designing Programs Some material based on material from Marty Stepp, Instructor, University.
M275 Arab Open University Faculty of computer Studies M275 - Web Development using PHP and MySQL FALL
C++ for Engineers and Scientists Second Edition Chapter 7 Completing the Basics.
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
1 Chapter 3 – Handling Strings and Arrays spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information Science and Technology.
Python Let’s get started!.
8 th Semester, Batch 2009 Department Of Computer Science SSUET.
Exception Handling and String Manipulation. Exceptions An exception is an error that causes a program to halt while it’s running In other words, it something.
Slide 1 PHP Predefined Functions ITWA113. Murach’s ASP.NET 3.5/C#, C1© 2008, Mike Murach & Associates, Inc. Slide 2 PHP Predefined Functions Objectives.
CSC 4630 Perl 3 adapted from R. E. Beck. Problem But we worked on it first: Input: Read from a text file named in a command line argument Output: List.
PHP Tutorial. What is PHP PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages.
Winter 2016CISC101 - Prof. McLeod1 CISC101 Reminders Quiz 3 this week – last section on Friday. Assignment 4 is posted. Data mining: –Designing functions.
13/06/ Strings Left, Right and Trim. 213/06/2016 Learning Objectives Explain what the Left, Right and Trim functions do.
Lesson 4 String Manipulation. Lesson 4 In many applications you will need to do some kind of manipulation or parsing of strings, whether you are Attempting.
Arrays and Strings. Arrays in PHP Arrays are made up of multiple memory blocks, each with the same name and differentiated by an index number Each block.
Python Let’s get started!.
Data Validation and Protecting Workbook
Algorithms Problem: Write pseudocode for a program that keeps asking the user to input integers until the user enters zero, and then determines and outputs.
Intro to PHP & Variables
Functions BIS1523 – Lecture 17.
String Manipulation Chapter 7 Attaway MATLAB 4E.
PHP.
Text Analyzer BIS1523 – Lecture 14.
String functions
Data Manipulation & Regex
Web Programming Language
Introduction to Computer Science
String functions
CIS 136 Building Mobile Apps
SEEM 4540 Tutorial 4 Basic PHP based on w3Schools
Presentation transcript:

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

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

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

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

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

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); ?>

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)

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

Faculty of Sciences and Social Sciences HOPE Leading Zeros printf(“%010d”,36); will print “ ”

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

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.

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!

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

Faculty of Sciences and Social Sciences HOPE How about now? <?php echo " "; printf(" Hello World!"); echo " "; ?>

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 " "; ?>

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 " "; ?>

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

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

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

Faculty of Sciences and Social Sciences HOPE What is echoed out? $studentID=(" "); if (strlen ($studentID) > 10) { echo ("Student Number is too many characters!"); } else { echo ("Student Number accepted"); }

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=(" "); if (strstr ($studentID,"0500")) { echo ("Student registered in 2005"); } else { echo ("Student did not register in 2005"); }

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"); }

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

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"); }

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). " "); }

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

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));

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));

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));

Faculty of Sciences and Social Sciences HOPE How could this be useful? if (substr($user , -2,2) == "uk") { echo ("UK customers pay £5 postage"); } else { echo ("You are not based in the UK, postage is £15"); }

Faculty of Sciences and Social Sciences HOPE A further refinement if (substr($user , -2,2) == "uk") { echo ("UK customers pay £5 postage "); if (substr($user , -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"); }

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

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;

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”);

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);

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);

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);

Faculty of Sciences and Social Sciences HOPE Converting Case PHP provides 4 functions that manipulate the case of a string – strtoupper(); – strtolower(); – ucwords(); – ucfirst();

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!

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”;

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

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

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; }

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

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; }

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; }

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

Faculty of Sciences and Social Sciences HOPE Spot the mistakes $mystring = “Last updated 2001” $mystring = substr_replace (mystring, “2007” -4, 4);

Faculty of Sciences and Social Sciences HOPE Spot the mistakes if (substr($user , -2,2) == "uk" echo ("UK customers pay £5 postage"); else echo ("You are not based in the UK, postage is £15");

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

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

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