52
www.hope.ac.uk Faculty of Sciences and Social Sciences HOPE PHP – Working with Files and Strings Stewart Blakeway FML 213 [email protected]

PHP – Working with Files and Strings

Embed Size (px)

DESCRIPTION

PHP – Working with Files and Strings. Stewart Blakeway FML 213 [email protected]. 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?. - PowerPoint PPT Presentation

Citation preview

www.hope.ac.uk Faculty of Sciences and Social Sciences

HO

PE

PHP – Working with Files and Strings

Stewart Blakeway

FML 213

[email protected]

www.hope.ac.uk Faculty of Sciences and Social Sciences

HO

PE

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

www.hope.ac.uk Faculty of Sciences and Social Sciences

HO

PE

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

www.hope.ac.uk Faculty of Sciences and Social Sciences

HO

PE

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

www.hope.ac.uk Faculty of Sciences and Social Sciences

HO

PE

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

www.hope.ac.uk Faculty of Sciences and Social Sciences

HO

PE

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

www.hope.ac.uk Faculty of Sciences and Social Sciences

HO

PE

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)

www.hope.ac.uk Faculty of Sciences and Social Sciences

HO

PE

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

www.hope.ac.uk Faculty of Sciences and Social Sciences

HO

PE

Leading Zeros

• printf(“%010d”,36);

• will print “0000000036”

www.hope.ac.uk Faculty of Sciences and Social Sciences

HO

PE

Other characters

• Other characters can be used instead of zeros

• they must be followed by a single quotation mark

printf(“%’*20d”,36);

******************36

www.hope.ac.uk Faculty of Sciences and Social Sciences

HO

PE

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.

www.hope.ac.uk Faculty of Sciences and Social Sciences

HO

PE

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!

www.hope.ac.uk Faculty of Sciences and Social Sciences

HO

PE

QuestionWhat 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

www.hope.ac.uk Faculty of Sciences and Social Sciences

HO

PE

How about now?

<?php

echo "<pre>";

printf(" Hello World!");

echo "</pre>";

?>

www.hope.ac.uk Faculty of Sciences and Social Sciences

HO

PE

Specifying a string length• You can specify a length of a string using the

same technique seen in padding.

<?phpecho "<pre>";printf("%20s<br />","Apples");printf("%20s<br />","Bananas");printf("%20s<br />","Pears");echo "</pre>";?>

www.hope.ac.uk Faculty of Sciences and Social Sciences

HO

PE

Specifying the string length• By default spaces are printed first• You can change this behaviour by using a -

<?phpecho "<pre>";printf("%-20s\n","Apples");printf("%-20s\n","Bananas");printf("%-20s\n","Pears");echo "</pre>";?>

www.hope.ac.uk Faculty of Sciences and Social Sciences

HO

PE

String Length$file = fopen("student_list.txt","r");

while (!feof($file))

{

echo "<pre>";

printf ("%100s<br />",fgets($file));

echo "</pre>";

}

www.hope.ac.uk Faculty of Sciences and Social Sciences

HO

PE

Arrays and Strings

• A string is an array of characters

$test=“Hello World!”

echo ($test[6]);

W

www.hope.ac.uk Faculty of Sciences and Social Sciences

HO

PE

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

www.hope.ac.uk Faculty of Sciences and Social Sciences

HO

PE

What is echoed out?$studentID=("05001221222");

if (strlen ($studentID) > 10){echo ("Student Number is too many characters!");

}

else{echo ("Student Number accepted");}

www.hope.ac.uk Faculty of Sciences and Social Sciences

HO

PE

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

}

www.hope.ac.uk Faculty of Sciences and Social Sciences

HO

PE

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

}

www.hope.ac.uk Faculty of Sciences and Social Sciences

HO

PE

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() – Not case sensitive

www.hope.ac.uk Faculty of Sciences and Social Sciences

HO

PE

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

}

www.hope.ac.uk Faculty of Sciences and Social Sciences

HO

PE

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

}

www.hope.ac.uk Faculty of Sciences and Social Sciences

HO

PE

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

www.hope.ac.uk Faculty of Sciences and Social Sciences

HO

PE

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

www.hope.ac.uk Faculty of Sciences and Social Sciences

HO

PE

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

www.hope.ac.uk Faculty of Sciences and Social Sciences

HO

PE

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

www.hope.ac.uk Faculty of Sciences and Social Sciences

HO

PE

How could this be useful?$userEmail=("[email protected]");

if (substr($userEmail, -2,2) == "uk"){echo ("UK customers pay £5 postage");}

else{echo ("You are not based in the UK, postage is £15");

}

www.hope.ac.uk Faculty of Sciences and Social Sciences

HO

PE

A further refinement$userEmail=("[email protected]");

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

www.hope.ac.uk Faculty of Sciences and Social Sciences

HO

PE

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

www.hope.ac.uk Faculty of Sciences and Social Sciences

HO

PE

What is echoed out?

$userString=("Hello everybody, it is a lovely day");

$delim = (" ");

$word = (strtok($userString, $delim));

echo $word;

www.hope.ac.uk Faculty of Sciences and Social Sciences

HO

PE

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

www.hope.ac.uk Faculty of Sciences and Social Sciences

HO

PE

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

www.hope.ac.uk Faculty of Sciences and Social Sciences

HO

PE

strip_tags()

• Strip tags is very useful for stripping html tags from a string

$mytext = (“<h1>Hello World!</h1>”);

echo strip_tags ($mytext);

www.hope.ac.uk Faculty of Sciences and Social Sciences

HO

PE

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

www.hope.ac.uk Faculty of Sciences and Social Sciences

HO

PE

Converting Case

• PHP provides 4 functions that manipulate the case of a string– strtoupper();– strtolower();– ucwords();– ucfirst();

www.hope.ac.uk Faculty of Sciences and Social Sciences

HO

PE

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

www.hope.ac.uk Faculty of Sciences and Social Sciences

HO

PE

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

www.hope.ac.uk Faculty of Sciences and Social Sciences

HO

PE

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

www.hope.ac.uk Faculty of Sciences and Social Sciences

HO

PE

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

1. Get users text

www.hope.ac.uk Faculty of Sciences and Social Sciences

HO

PE

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

www.hope.ac.uk Faculty of Sciences and Social Sciences

HO

PE

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

www.hope.ac.uk Faculty of Sciences and Social Sciences

HO

PE

3. Check spellingfunction 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; }

www.hope.ac.uk Faculty of Sciences and Social Sciences

HO

PE

4. Output the spelling mistakes

• Create a function called display– accept one argument– echo the argument

function display ($txt){echo $txt;}

www.hope.ac.uk Faculty of Sciences and Social Sciences

HO

PE

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

www.hope.ac.uk Faculty of Sciences and Social Sciences

HO

PE

Spot the mistakes

$mystring = “Last updated 2001”

$mystring = substr_replace (mystring, “2007” -4, 4);

www.hope.ac.uk Faculty of Sciences and Social Sciences

HO

PE

Spot the mistakes$userEmail=([email protected]);

if (substr($userEmail, -2,2) == "uk"

echo ("UK customers pay £5 postage");

else

echo ("You are not based in the UK, postage is £15");

www.hope.ac.uk Faculty of Sciences and Social Sciences

HO

PE

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

www.hope.ac.uk Faculty of Sciences and Social Sciences

HO

PE

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

www.hope.ac.uk Faculty of Sciences and Social Sciences

HO

PE

Any Questions?

• Next Week– connecting to a SQL Server– creating a Database– selecting a Database– adding to a Database