Lecture 11 Log into Linux, also log into csserver Reminder: Project 3 due next Tuesday Questions? Thursday, September 30 CS 375 UNIX System Programming - Lecture 11 1
Outline More PHP Remote files Directory operations Functions Variable scope Interacting with the OS Regular expression matching and substitution Thursday, September 30 CS 375 UNIX System Programming - Lecture 11 2
Remote Files Since PHP was designed for use with web servers, the fopen( ) command can be used to access remote files by giving a URL instead of a local file name. $slash = fopen("http://www.slashdot.org", "rt"); $site = fread($slash, 200000); // 1st 200K bytes fclose($slash); print $site; Thursday, September 30 CS 375 UNIX System Programming - Lecture 11 3
Directory Operations PHP directory operations are similar to C: opendir( ) , readdir( ) , and closedir( ) . $handle = opendir ("."); // current dir if ($handle) { // check that open succeeded while (false !== ($filename = readdir($handle))){ if ($filename != "." && $filename != "..") print "$file\n"; } closedir ($handle); } The use of !== (not identical to) is to handle the possibility that a directory entry name evaluates to false. Thursday, September 30 CS 375 UNIX System Programming - Lecture 11 4
Directory Operations Other directory operations include: mkdir ( ) - create a directory rmdir ( ) - remove an empty directory get_cwd ( ) - get the current working directory chdir ( ) - change directories Thursday, September 30 CS 375 UNIX System Programming - Lecture 11 5
Functions PHP functions are defined as in C++ without the types using the function keyword. Has both value and reference parameters. function foo ($arg1, &$arg2) { $result = ...; // local variable ... return $result; } Function definitions can appear anywhere in the script. Thursday, September 30 CS 375 UNIX System Programming - Lecture 11 6
Default Parameters PHP has default parameters function doHello ($name = "Mary") { return "Hello $name!"; } doHello(); // "Hello Mary!" doHello("John"); // "Hello John!" Thursday, September 30 CS 375 UNIX System Programming - Lecture 11 7
Variable Arguments A PHP function may be called with more arguments than listed in its header. The extra arguments can be accessed using functions func_num_args( ) , func_get_arg( ) , and func_get_args( ) . function someFunc ($a) { for ($i = 0; $i < func_num_args(); ++$i) { $param = func_get_arg($i); print "Received parameter $i: $param\n"; } $params = func_get_args(); $paramlist = implode(",", $params); print "Received parameters: $paramlist\n"; } someFunc (5,4,3,2,1); Thursday, September 30 CS 375 UNIX System Programming - Lecture 11 8
Variable Scope In PHP, any variable not set inside a function is considered global . That is, they are accessible from anywhere else in the script, except inside a function. In particular, this means that variables span any code islands in the script Variables set inside functions are local to that function. Thursday, September 30 CS 375 UNIX System Programming - Lecture 11 9
Superglobal Variables Special variables like $_SERVER are called superglobals , since they are accessible anywhere, including inside functions. $GLOBALS is a superglobal associative array that gives access to any global variable. The name of the variable is the index. Thursday, September 30 CS 375 UNIX System Programming - Lecture 11 10
Scope Examples $bar = "baz"; print "global \$bar is: $bar\n"; // baz foo1(); print "global \$bar is: $bar\n"; // baz print "global \$foo is: $foo\n"; // null foo2(); print "global \$bar is: $bar\n"; // wombat function foo1 () { print "local \$bar is: $bar\n"; // null $foo = "foo"; print "local \$foo is: $foo\n"; // foo } function foo2 () { $GLOBALS['bar'] = "wombat"; } Thursday, September 30 CS 375 UNIX System Programming - Lecture 11 11
Interacting with the OS Backticks (`) can be used to run external commands, including using redirection or pipes . $cwd = `pwd`; print "Current directory is $cwd\n"; print "The files in the directory:\n"; print `ls`; Thursday, September 30 CS 375 UNIX System Programming - Lecture 11 12
Regular Expression Matching When the basic string operations are not enough, PHP provides regular expression (regexp) matching. The basic regexp function is preg_match( ) that has two parameters, the pattern to match and the string to match it against. It returns true after the first match; false if there is no match. Regexps are formed by starting and ending with a (forward) slash. E.g., "/php/" Thursday, September 30 CS 375 UNIX System Programming - Lecture 11 13
Regexp Special Characters The special characters used to form regexps are similar to those used in shell globbing or grep. \ De-special the next character | Alternation (or) () Group [] A character class ^ Match at beginning of string $ Match at end of string . Match any one character, except \n Thursday, September 30 CS 375 UNIX System Programming - Lecture 11 14
Regexp Quantifiers Quantifiers indicate how many times the preceding item should match. * Match 0 or more times + Match 1 or more times ? Match 0 or 1 times {COUNT} Match exactly COUNT times {MIN,} Match at least MIN times {MIN,MAX} Match between MIN and MAX times Thursday, September 30 CS 375 UNIX System Programming - Lecture 11 15
Regexp Examples Here are some regexp examples: "/Gandalf|Saruman/" # Match either "/pro(b|r)ate/" # probate or prorate "/\..$/" # file.a, xxx.b, etc at end "/could(n't)?/" # Match could or couldn't "/^ba(na)*/" # At start: ba,bana,... "/ba(na){2}/" # banana Thursday, September 30 CS 375 UNIX System Programming - Lecture 11 16
Regexp Modifiers A regular expression can be followed by modifiers that affect the way matches are computed. Common modifiers include i Case insensitive m Let ^ and $ match next to embedded \n Thursday, September 30 CS 375 UNIX System Programming - Lecture 11 17
Modifier Examples preg_match("/php/", "php"); // true preg_match("/php/", "PHP"); // false preg_match("/php/i", "PHP"); // true preg_match("/Php/i", "PHP"); // true $multiline = "This is\na long test\nto see whether\nthe dollar\nSymbol\nand the\ncaret\nwork as planned"; preg_match("/is$/", $multiline); // false preg_match("/is$/m", $multiline); // true Thursday, September 30 CS 375 UNIX System Programming - Lecture 11 18
Regexp Symbols There are special symbols that can be used inside regular expressions. Most common ones: \b Match word boundary \B Match non-word boundary \s Match any whitespace \S Match any non-whitespace \A Match string beginning (^) \Z Match string end ($) The last two are used with multi-line strings ('m' modifier) where ^ and $ will match each line rather than the whole string. Thursday, September 30 CS 375 UNIX System Programming - Lecture 11 19
Regular Expression Substitution The function to use regexps to identify text to be replaced is preg_replace( ), which takes 3 arguments, the regexp, the replacement string, and the string to work with. It returns a string with the matches replaced. The replacement string can contain $n to refer to the match of subpattern n of the regexp rule. $0 refers to the entire matched text. Thursday, September 30 CS 375 UNIX System Programming - Lecture 11 20
Substitution Examples $a = "Foo moo boo tool foo"; $b = preg_replace("/[A-Za-z]oo\b/", "Got word: $0\n", $a); print $b; // Output: // Got word: Foo // Got word: moo // Got word: boo // tool Got word: foo $match = "/the (car|cat) sat on the (drive|mat)/"; $input = "the cat sat on the mat"; print preg_replace($match, "Matched $0, $1, and $2\n", $input); // Output: Matched the cat sat on the mat, cat, and mat Thursday, September 30 CS 375 UNIX System Programming - Lecture 11 21
In-class Exercise Write a PHP program that tests whether or not an argument is a valid phone number (based on its format) and print an appropriate message. The following should be considered valid phone numbers: (123)456-7890, 123-456-7890, (123)4567890, 123 456 7890, 123.456.7890, 1234567890, etc. Thursday, September 30 CS 375 UNIX System Programming - Lecture 11 22
Recommend
More recommend