PHP 4 for Beginners
- a tutorial
By Ranjan Chari,
2003
©
2003 Ranjan Chari
This tutorial may
be reproduced without any modifications to this document for non-commercial,
non-profit purposes. All other forms of usage requires the permission of the
author - Ranjan Chari, email: ranjan@bigappledesigns.com
|
Foreword Introduction PHP is a successor of an older product called PHP/FI. This was a product created by Rasmus Lerdorf in 1995 and consisted of a bunch of Perl scripts for which kept track of user accesses to his resume. 'PHP' stood for 'Personal Home Page and 'FI' stood for 'Form Interpreter'. These scripts got a whole lot of attention from the programming communities and subsequently resulted in the birth/re-birth of PHP as we know it today. The name stands, now, for 'Hypertext Pre-Processor' which is a 'GNUish' derivative of the name. PHP today runs on millions of websites and is a direct competitor to non-open source products such as ASP from Microsoft, ColdFusion from Macromedia etc. Now you may ask, 'What's the benefit of using PHP over ASP or ColdFusion ?' There are many supporting answers, one of them being - "it makes sense to use a free product that offers all the functionality of paid products, greater platform support and which has support available all across the world." Some reasons are 1.
PHP is free. It's Open Source. What does PHP do and how do I run it ? PHP is an interpreted language which works in conjunction with a webserver. It allows static HTML pages to have 'intelligence'. By this I mean that it will allow you do many more things than what you can accomplish via a simple HTML page. PHP is embedded into HTML. When a PHP page on a webservers is run, the webserver passes the PHP code to the PHP interpreter which in turn performs some actions, an example being communicating with a database or performing some calculation' and passes the result back the webserver. The end result, i.e. the page displayed to the browser is plain old HTML. In the case of Apache, PHP can be installed as an addon module. This means that Apache can be compiled for your system with PHP built into it. The clear advantage here is that if PHP is integrated into the webserver, you have a tightly integrated product that delivers superior performance as compared to a CGI model where information is exchanged between the webserver and a CGI module. PHP works especially well under Linux/UNIX and with Apache. Windows support is present and is especially useful for development and testing purposes because most people do not have access to a Linux/Unix box and people seem to be most familiar with Windows based systems. My intention here is to tell you that for a live environment, it's better to have a PHP driven website running on a Linux/Unix box with Apache rather than Windows and IIS. Of course this is only a comparative comment. PHP works fine under Windows. And you should work with whatever operating system you are comfortable with. Plenty of online tutorials are available for installations under various environments including the Mac. PHP can be
run Windows 95/98/2000/XP/NT/ME, Linux, FreeBSD, Unix/HP-UX,Mac OS X,OpenBSD,
Solaris and other Unix variants. For this
tutorial I am working with Apache and Windows XP and we will be using
PHP as a CGI with MySQL support built-in. That said, let's get started with creating an environment where we can start learning PHP. Intalling
PHP 4 and creating a development and testing environment So what do we need to do:
All of this is being done on a Windows XP system. These steps should work the same on Windows 2000 and ME. On Windows 9x and NT you'll need a software package to be installed called InstMSI.exe. This package is available at microsoft.com. Windows 95 users require an update called the Windows 95 Socket 2 update which solves a number of Winsock2 and TCP/IP stack issues. Again, this is available at microsoft.com. You can download the products by clicking the links provided above. Save everything in a directory that you can easily find later on. All of these products have several mirrors around the world. You may use any of them as long as you get a current product. If you get corrupted downloads from several locations then try disabling your download accelerator software if any is installed. The product
versions that we need are:
>
INSTALL Apache Steps 2. Accept the terms. Hit 'Next' 3. Read about the HTTP server. Hit 'Next' 4. Server Information: Network Domain:
'xyz.com' or simply 'user' Leave the radio button on it default state for 'all users' Hit 'Next' 5. Setup Type: Typical Hit 'Next' Install the software. Apache will successfully install and you should get a small Apache icon on the taskbar. Open up a browser window and try this: or both are 'loopback' addresses and your browser will pull up the webpage hosted by the Apache webserver you just installed. If you see the Apache test page you are fine. If not then check the install. Do you need to launch the service manually ? >
INSTALL PHP Steps 2. The default directory C:\PHP is fine. Hit 'Next' 3. Mail Configuration: Your SMTP server is "localhost", email is your email address. Hit 'Next' 4. Server Type: Apache Hit 'Next' 5. Now since we are using Apache we need to edit the httpd.conf file manually since this PHP installer does not does automatic configurations (yet) for Apache. So go to the program group created for Apache from your 'Start' menu and go to 'Configure Apache Server'. There you'll find a link to a text document called httpd.conf. Click it to open it in notepad.exe. Search for something that looks like this: # DocumentRoot:
The directory out of which you will serve your Modify the DocumentRoot to be: DocumentRoot "C:/www" This directory will be the default place where all the pages are going to be served from. This is for convenience. Who likes to dig inside the Program Files directory area ? So go ahead and create a directory called 'www' on your C: drive. Search for something that looks like this: # AddType
allows you to add to or override the MIME configuration and below that add the following lines so the text looks like this: AddType
application/x-tar .tgz All that you're doing here is to tell the Apache webserver where to find the PHP interpreter and which filename extensions to associate with PHP. Now locate text that looks like this: # Change
this to Listen on specific IP addresses as shown below to Listen
127.0.0.1:80 Change the 'Listen Parts' to the IP addresses show above. This will ensure that your development server listens to Port 80. 127.0.0.1 is a loopback IP address that will ensure that the browser tries to communicate with the Apache server on your system. Save and close the file. Stop Apache and then start Apache. Now using any text editor such as notepad create a test php file. Insert the following code in the text document and save it as 'test.php' ( Remember that the extension should be .php) <? phpinfo()?> Now open up http://localhost/test.php in your browser. This php snippet will run and present you with PHP environment variables and other information. If this happens, you have successfully installed PHP and it's talking nicely with your webserver. >
INSTALL MySQL Steps 2. Execute WinMySQLAdmin 3. Create
a Username and Password 4. Now open up the DOS (Command) prompt: Type this:
C:\cd
mysql\bin Hit 'Enter' Then type: C:\mysql\bin\mysql Hit 'Enter' If you see something like ... C:\mysql\bin>mysql Type 'help;' or '\h' for help. Type '\c' to clear the buffer. mysql> ...your MySQL install was successfull. (The test here is that the mysql monitor will not run without a MySQL daemon running on the system already.) Okay, we're done with the install. If you encounter problems at any stage check php.net, apache.org, mysql.com for new installation instructions, feedback and for installation instructions on other operating systems and webservers. Please note that the code you're going to write, will work the same regardless of where you run them as long as PHP4 is installed. Selecting a Text Editor Now that we're going to start actual coding you need to get hold of a decent text editor. By decent I mean a text editor that than provide you with multiple windows to look at two scripts simultaneously, syntax highlighting, line numbering, some text formatting functions, some search functions etc. I use TextPad as I am comfortable with it and have been using it for some time. UltraEdit, EditPlus, WinSyntax, DreamWeaver UltraDev/MX, Visual Studio are other alternatives in varying degrees of complexity and pricing. See what you have or what you like and go for something you'd want to use often. It pays to learn a smaller package better than a larger package 'less better'. Of course your choices are also limited by your operating system. It may be true that you may just have to work with vi and pico on Linux. Anything that can write ASCII text will work fine for our purposes since code length is relatively small. PHP Basics > PHP Tags PHP code is embedded in tags. These are special tags that let the webserver know which parts of an HTML page are PHP. Just like HTML tags we need to open and close tags. PHP tags can be written as: <? some code goes here ?> or <?php some code goes here ?> The second variant is the more commonly used syntax and which will be used throughout this tutorial. > echo and print <?php echo "Hello World"; ?> Look at the syntax. Note the ' " ' and the ' ; '. All textual information needs to go inside double inverted commas. All statements need to end with a ';'. The syntax will seem familiar to PERL programmers. Save this
file as echo.php and view it thru your browser by going to the loopback
address. http://localhost/echo.php <?php echo ("Hello World"); ?> The example above does the exact same thing as the first example. You're just using a syntax variant. But... <?php echo ("Hello World","Hello"); ?> This will give you a parse error. But if you remove the parenthesis, it's work fine. So it's obvious that using the parenthesis limits you to a single 'argument'. If you look at the source of the page generated by either of these two examples, you'll notice that there is no HTML. It's just text that got printed out. This is because we've not specified that any HTML to be printed. <HTML> echo "Hello
World<BR>\n"; ?> </BODY> So what does
this example do ? The output: Hello World The HTML source of the generated page: <HTML> Hello World<BR> By looking at the PHP code and the output we understand the following: 1. PHP can
be stuck inside html using the opening and closing <?php tags. <?php echo (2+2); ?> This code above will output '4'.
echo (2+2).("Hello World")); ?> The code above will print out '4HelloWorld' The parenthesis are required to separate the two logical entities. The period '.' joins the sum of 2+2 and the string provided in the output. So essentially if you have two strings and you'd like to display them together in the output use a period. You must note that the 'print' function can take only a single argument. Variables & Syntax A variable is a container. It contains some information that will be used in your program. Variables are case sensitive. Variables are declared with a '$' sign. Look at the example below: <?php $myname="Ranjan"; $mynumber=2; $myaddition=2+4; $mymismatch = 3+"hoopla"; print "$myname <BR>"; print "$Myname <BR>"; print "$mynumber <BR>"; print "$myaddition <BR>"; print "$mymismatch <BR>"; ?> The output is: Ranjan As you can see $mymismatch does something different. It ignores the "hoopla" value. PHP is very easy with work with, with respect to variable assignments. You can assign any value to a variable at any time and interchangeably. This means that if you start of by declaring that a variable has numerical value and later assign a string value to it, it's perfectly legal. <?php $var1=300; $var2=3; $var3=$var1 + $var2; $var4=$var1/$var2; $var5=$var1%$var2; $var6=($var1-$var2)*$var4; print "$var3 <BR>"; print "$var4 <BR>"; print "$var5 <BR>"; print "$var6 <BR>"; ?> The Output: 303 Notice how the addition, multiplication, subtraction, modulus 'operators' are used. Whenever you need to perform a mathematical operation you need to use an 'operator'. <?php //Some comments #Some comments /* My comments on multiple lines */ ?> The example above shows various methods to comment code in PHP. You have two options to write single line comments and one option to write multi-line comments. Commenting code is always a good idea, once code get's complex, little notes always help the next time you get around looking at the code. Variables can be accessed anytime and anyplace within your PHP code. So if a variable is declared once, it's available to you always. The only time variables are not available 'globally' are when they are declared inside 'functions'. More on 'functions' later. Quotation Marks PHP code uses single and double quotation marks in it's coding syntax. When you use double quotes, the string enclosed within them is processed. Any variables inside that can be processed is processed and the actual or resultant value is substituted. <?php $var1="BMW"; $var2=1+6; print "$var1"."$var2"."<br>"; print '$var1 $var2'; ?> Output: BMW7 Note that with single quotes, stuff is printed the way it exists. With Double quotes variable substitution has been done do provide the final value. This process of substitution is called 'variable interpolation' in geekdom. To put a single quote or a double quote within single or double quotes, just put in a backslash (/) right before it. Backslashes are called 'escape' characters. Arrays An array is a variable that contains multiple values and where each value can be indexed individually. $mycar="Honda Accord"; The example above is an array with one value. Now let's say you wanted to store the names of multiple cars in the variable $mycar and wanted the ability to reference any variable individually. <?php $mycar[0] = "Honda Accord"; $mycar[1] = "Maserati"; $mycar[2] = "Honda Element"; $mycar[3] = "Toyota Celica"; print $mycar[0]." ".$mycar[1]." ".$mycar[2]." ".$mycar[3]; ?> Output: Honda Accord Maserati Honda Element Toyota Celica Arrays can be used to store a bunch of related or un-related information that can be accessed using a 'key'. A key can be an integer (numeral) or a string. The example above uses a numbers as keys. By calling a key you can extract the value of that key from the array. Let's look at some more examples to understand arrays clearly. <?php $mycar = array('Honda Accord', 'Maserati', 'Honda Element', 'Toyota Celica'); print $mycar[0]." ".$mycar[1]." ".$mycar[2]." ".$mycar[3]; ?> Output: Honda Accord Maserati Honda Element Toyota Celica In the example above we have used a different style of defining an array. By default array keys are integers and begin with Zero. <?php $mycar = array('firstcar' => 'Honda Accord', 'secondcar' => 'Maserati', 'thirdcar' => 'Honda Element', 'fourthcar' => 'Toyota Celica'); print $mycar['firstcar']." ".$mycar['secondcar']." ".$mycar['thirdcar']." ".$mycar['fourthcar']; ?> Output: Honda Accord Maserati Honda Element Toyota Celica The example above uses strings as keys. <?php $mycar = array('firstcar' => 'Honda Accord', 'secondcar' => 'Maserati', 'thirdcar' => 'Honda Element', 'fourthcar' => 'Toyota Celica'); echo $mycar['thirdcar']; ?> Output: Honda Element You can access any value by calling the corresponding key in the array. Now let's assume you need to create an array that holds numerical as well as string values. $myarray = array('myfirst' =>' One', 'mysecond' =>2, 'mythird' => 'Three'); That is perfectly legal in PHP. Here are some more examples illustrating some more functions relevant to arrays. <?php $myarray = array('myfirst' =>' One', 'mysecond' =>2, 'mythird' => 'Three'); $myarray['myfourth'] = '4'; ### This sizeof() function will return 4 which is the size of the array. echo sizeof($myarray)."<BR>"; ### Takes an array as the argument and convert each key-value pair into a variable and value pair. extract($myarray); echo $myfirst."<BR>"; ?> There are several more functions that deal with arrays, some have been listed below. For a complete list visit the php.net site. <?php $mostactive = array('MSFT','ORCL','IBM','DELL','INTC','NT'); // Does a string exist in an array ? True if it does, False if does not. echo in_array('MSFT', $mostactive)."<BR>"; // Searches for a value in an array and return the position of the value if found. echo array_search('INTC', $mostactive)."<BR>"; // Assigns
the value of array elements to variables. In this case the first two values
in the array list ($a, $b) = $mostactive; echo $a."<BR>"; // Add a new value to the end of an array array_push($mostactive, 'MMM'); echo $mostactive[6]."<BR>"; // Remove a value from the end of an array array_pop($mostactive)."<BR>"; // Remove a value from the top of an array array_shift($mostactive); echo $mostactive[0]."<BR>"; // Add
a value to the top of an array echo $mostactive[0]."<BR>"; ?> Output: 1 Lets take a look at a simple way to examine arrays. <?php $mostactive = array('MSFT','ORCL','IBM','DELL','INTC','NT'); //print_r( ) recursively prints out the key and values for an array print_r($mostactive); ?> Output: Array ( [0] => MSFT [1] => ORCL [2] => IBM [3] => DELL [4] => INTC [5] => NT )
Multi-Dimensional Arrays Let's say you have 3 friends. Each friend has a car and lives in a different city. Lets say you wanted to keep all this info in an array. You'd look at creating a multi-dimensional array. Accessing multi-dimensional arrays is very similar to single level arrays. <?php $mybuddies = array( "names"
=> array('buddy1' => 'Larry', "cities"
=> array('city1' => 'New York', "cars"
=> array('car1' => 'Dodge Viper', echo
$mybuddies['names']['buddy1']."<br>"; ?> Output: Larry The array here is arranged for better readability. Essentially we are defining a whole bunch of arrays inside an array. When accessing a key we are specifying the container array, followed by the sub-level array followed by the key. That's all there is to it. Control Statements Control statements are statements inside a program that execute bits of code depending on conditions. Control statements are present in every programming language. Control statements in all programming languages work quite the same. Because logic is universally accepted to be similar. For example
you'd use an umbrella 'if' it were raining 'or' if it were really sunny
and you wanted to protect your skin from sunburn. There are many types of control statements. Each is ideal in a certain kind of scenario. Let's examine these control statements and when to use them. To create a program where decisions can be taken, we need to understand a few operators. When we compare two values we use 'comparison operators'. Comparison Operators = =
The Equal Operator: True if two values are equal to
each other. Otherwise False Logical Operators and Is
true when both arguments are true If-else This type of conditional control statement executes block of code depending on whether a test condition is true or false. In the example below $x is compared with $y. If $x is less than $y, a block of code is executed. If $y > $z a block of code is executed. If that fails, another block of code enclosed within an 'else' control statement is executed. An 'if' control statement can be executed without a corresponding 'else' statement. But an 'else' statement cannot exist on it's own. <?php $x=1; $y=6; $z=8; if ($x < $y) { if ($y > $z) {
{ ?> Output: X is less
than Y Now lets say you wanted to test for several conditions which are related, there is a variant of the If-else control statement. Elseif <?php $budget=25000; if ($budget == 210000) { print "You can buy a Bentley Arnage";} elseif ($budget == 231000) { print "You could buy a 2003 Aston Martin V12 Vanquish"; } elseif ($budget == 80000) { print "You could buy a Mercedes Benz S Class Sedan"; } elseif ($budget == 37000) { print "You could buy a Mercedes-Benz C320"; } elseif ($budget < 30000) { print "You could buy an Audi A4 1.8T"; } ?> Output: You could buy an Audi A4 1.8T Okay, so what have we done here ? We have successfully created a series of decisions based on certain conditional arguments. Note the we have used the '= =' equivalence operator to check for equivalence comparison. If we had another 'elseif' statement after the last 'elseif' statement it would not be evaluated. Actually after any one condition is successfull, no other checks are performed. Switch The switch control statement allows conditional execution of code depending on the value of a single expression. <?php $match=6; switch($match) { case 1: print "The value is 1"; case 2: print "The value is 2"; case 3: print "The value is 3"; case 4: print "The value is 4"; case 5: print "The value is 5"; case 6: print
"The value is 6"; default: print "Nothing was found"; } Output: The value is 6 From the example above we notice that, the switch statement evaluates against a single expression. Unlike the 'elseif' statement, the switch statement will continue to evaluate subsequent expressions even if a true condition is found. A special statement called 'break' needs be used to prevent further examination of conditions once a match (true condition) is found. The 'default' statement is used to indicate an action that will be performed if everything else fails. The swtich statement is a clean way to test for multiple values of a single argument or expression. Loops Looping is a very powerful and commonly used programming technique. In theory there are two types of loops. 'bounded' and 'unbounded' loops. A bounded loop will execute a certain number of times. An unbounded loop will execute till the time a certain condition become true or false. While The while loop checks a condition as a boolean and executes a statement. It keeps doing this again and again as longs as the condition is true. <?php $x=2002; while ($x<2003 && $x>2001) { print "the year of the Horse"; } ?> The Output here would 'the year of the Horse' repeated across the screen many times. You can make all kinds of conditions for example: if $x !=0 or if !$x etc. Do-While A close relative of the While loop, this kind of loop executes a statement atleast once, then checks a condition and if it's still true executes the statement again. <?php $counter=90; do { print "The current value is $counter <BR>"; // Same
as $counter=$counter+1; Other syntax variants $counter-- $counter++; } while ($counter <=100) ?> Output: The current
value is 90 the FOR loop <?php for ($x=30; $x<=100; $x++) { print "The Value of x is $x <br>"; } ?> This is an example of an unbounded FOR loop. Essentially an unbounded loop is made into a bounded loop using conditions. In the example above the for statement has 3 conditions. Each is separated by a semi-colon. The first is the initial expression. The second is the check condition. The third is the loop expression. The loop expression is executed at the end of every loop. The statements inside the 'for' loop get executed each time the loop does a loop. In the example above, leaving out the '{' and '}' would work fine but it looks more organized this way. Nested Loops Loops can be placed inside loops for interesting results. An example to illustrate a scenario where you'd need to do this. Lets say we need to print the multiplication tables for 5 to 10 and upto 12 multiplication values. We can do this using loops. <?php for ($x=5; $x<11; $x++) { for ($y=1; $y<13; $y++) { print "$x multiplied by $y"." = ".($x * $y)."<BR>"; } print "<BR>"; } ?> Output: 5 multiplied
by 1 = 5 . 10 multiplied
by 1 = 10 The example above iterates from 1 to 12 for each multiplication table value between 1 to 10. Is'nt this cool! Loop and Control Statement Terminators Often you might want to exit out of a loop. PHP has two constructs to do just this. exit( ) and die ( ). <?php for ($x=5; $x<11; $x++) { for ($y=1; $y<13; $y++) { print "$x multiplied by $y"." = ".($x * $y)."<BR>"; } die("This is getting boring"); } ?> Output: 5 multiplied
by 1 = 5 die( ) is useful when you want to stop execution of a loop for any reason and exit with an informative message. Using exit( ) in this example will do exactly the same thing but exit is useful when you want to get out of a script right then and there. die( ) on the other hand is useful to test for a certain condition and if it's true exit the whole program with a useful message. Functions Functions are pieces of code that you can re-use. All that you need to know is what kind of input it requires and you get the desired output. For example echo( ) is a function. So is die( ) and every other command we have used till now. These are functions that have programmed by the PHP developers. But we can create our own functions. Functions help in providing us with the ability for procedural abstraction. Essentially it means that you can create blocks of code which can be reused for different tasks. For example if you knew that you'd need to use a lot of actuarial (insurance) formulae in your programs, you could create a set of functions that would let you perform these formulae without re-writing them for each program. <?php function tolkien() { tolkien(); ?> Output: Lord of the Rings <?php function totalincome($mysalary, $mydividend, $myinterest) { totalincome(60000, 1000, 200); ?> Output: My total income is:61200 In these two examples we see that functions can work with or without arguments passed on to them. Functions can be useful in large programs with repetitive tasks. Remember variables declared inside a function are not available outside a function. <?php totalincome(60000, 1000, 200); print $adder; function totalincome($mysalary, $mydividend, $myinterest) { ?> Output: 61200 The example above illustrates that you can place functions any where in the program. PHP4 actually pre-compiles the program to see where functions occur. This used to be different in PHP3. The 'global' declaration makes the variable scope 'global'. You can store functions in include files. These are files that can be called from within a php program (script) and would be then considered to be part of the program. This is useful when you need to use the same functions over multiple pages. The syntax is: <?php include "my_functions.inc"; ?> Let's look at some more function examples. Till now we have seen that functions can be passed some arguments which are acted upon. Now lets see how to pass some information between functions. The code below illustrates the use of the command 'return'. return sends back the resulting value of the statements that were executed within the function. In the example below, a function addme( ) has been created which adds two numbers. The second function multme( ) multiplies two numbers. The resulting value ($val) is returned and the value is assigned to $mysum. $mysum is used in turn in multme( ). The resulting value is again passed back and assigned to $mymult. <?php function addme($x, $y) { function multme($x, $y) { $mysum = addme(10, 15); $mymult = multme($mysum, 20); echo($mymult); ?> Output: 500 <?php function cities($a="phoenix", $b="seattle", $c="san francisco") { echo "$a
<br>"; } cities(); ?> Output: The above example shows a variant of assigning argument values inside a function. Strings and Regular Expressions It's obvious that strings are going to be used in almost all programs. It become imperative to know ways to do things with strings, to search for patterns. How do you count the number of characters in a string ? Does a string contain a vowel ? We'll to do stuff like this, we have some really handy built-in PHP functions and certain methods for searching and sifting through strings called Regular Expressions. PERL users would realize how useful PERL's powerful regular expression capabilities are - we'll PHP is quite strong with string manipulation too. <?php $mytext = "I think 640k should be more than enough for anyone"; print "$mytext <BR>"; print strtolower($mytext)."<BR>"; print strtoupper($mytext)."<BR>"; print ucfirst(strtolower($mytext))."<BR>"; print ucwords($mytext)."<BR>"; ?> Output: I think 640k
should be more than enough for anyone strtolower(
) : Converts a string to lower case Let's look at some more string functions. <?php $mytext
= "My broker told me that ING is a good investment"; // addslashes( ) adds backslashes where necessary. print addslashes($moretext)."<BR>"; // stripslashes( ) strips the backslashes addres before special characters. print stripslashes(addslashes($moretext))."<BR>"; // explode(
) take a string separator, in this case it's a space, a string and $myarray=explode(" ", $mytext); // The
while loop here uses the each( ) function to loops that many times as
there while ($myvar= each($myarray)) { echo $myvar["key"]; } echo "<BR>"; //implode( ) is the opposite of explode( ) $myoriginaltext = implode(" ", $myarray); print "$myoriginaltext <BR>"; //strlen( ) counts the number of character in a string including whitespaces $mystringlength = strlen($myoriginaltext); print "The number of characters in the string is: $mystringlength <BR>"; ?> Output: His actual
words were \"Buy it for the long term\" My broker
told me that ING is a good investment Another example: <?php $mytext="The quick brown fox jumped over the lazy dog"; // 3 arguments
are provided. print substr($mytext, 0, 5)."<BR>"; // Here the
start position is 5, the negative (-4) specifies the end position counting
backwards from print substr($mytext, 5, -4)."<BR>"; // In the
example below, the start point is only specified. The end point by default
is the end of the print substr($mytext, 2)."<BR>"; ?> Output: The q Regular Expressions Well we looked at some string functions. Now let's take a look at regular expressions. PHP provides two styles of regular expression syntax. Posix and PERL. Posix is the default syntax. If you'd like to use PERL syntax for regular expressions you need to compile in the PERL compatible regular expression library. We'll stick with Posix. Regular expressions are ways in which patterns within text can be described. Let's see a few examples with ereg( ) which is the most common regular expression function. <?php $mytext="The quick brown fox jumped over the lazy dog who has been eating too much";
$bool=ereg("^The", $mytext); // In this instance $bool has a match. So it's content will be = 1; print $bool."<BR>"; // '$' matches a sub-string at the end of a string. The example below again would be true. $bool=ereg("much$", "$mytext"); print $bool."<BR>"; ?> Let's explore regular expressions deeper. ^mystring - will match a string beginning with 'mystring'. So 'mystring is a long string' will match. But ' I have a long string called mystring' will not match. mystring$ - will match any string ending with 'mystring'. 'This is mystring' will be a match. Wildcards We have 3 wildcard modifiers that can add greater flexibility to our regular expression search. * :Match zero or more instances + :Match one or more instances ? :Match only zero or one instance 'am+' will match 'am i alive ?', 'amadeus' etc. 'micros?' will match 'micro', 'microsoft'. The '?' modifier excluded the preceeding character from it's match. 'ar*' will match 'argentina', 'arable', 'arabia' etc. Bounds Lets say we wanted to match 'mxxx' within a string. Should we write 'mxxx*' ?. What if we needed the character 'm' followed by exactly 3 'xxx'. mx{3} : match the character 'm' followed by exactly 3 'x's. mx{1,3} : match the character 'm' followed by a minimum of 1 'm' and a maximum of 3 'x's. mx{2,}: match the character 'm' followed by atleast 2 'x's. mx.x : The period here is a wildcard. This will match 'mxyx', 'mxtx' etc. r(an)+ : match the character 'r' followed by 'a' and 'n'. The parenthesis indicates a sequence of characters that need to be evaluated together. So 'random', 'randomize', 'ranaway' will all match. ^me | ^you : match any string beginning with 'me' OR 'you. The pipe here represents an 'OR' operator. Character Ranges [xyz] : match a string containing x, y or z. [a-z] : match a single lower case letter from 'a' to 'z' [a-zA-Z] : match a single lower case letter or upper case letter from 'a' to 'z' or 'A' to 'Z' [1-4] : match a single digit from 1 to 4 [a-zA-Z0-9] : match any alphanumeric character [^1-4] : match anything but characters 1,2,3,4. : A carat within a square bracket negates the matching criteria. (Read as 'don't match') A useful function for looking through strings and replacing a part of it is: ereg_replace( ) The syntax is: ereg_replace(pattern, replacement, string) And here's an example: <?php $mystring = "With great power, comes great responsibility"; print "The original string is: \"".$mystring."\""."<BR>"; $modistring = ereg_replace("great","awesome",$mystring); print "The modified string is: \"".$modistring."\""."<BR>"; ?> Output: The original
string is: "With great power, comes great responsibility" Date and Time functions Time and Date in PHP are dependent on the timestamp which is the number of seconds between January 1, 1970 and the current date and time. January 1970 has something to do with the invention of Unix and this time is also called the Unix Epoch time or Time 0. This timestamp can be obtained by using the time( ) function. It will return the number of seconds elapsed since January 1, 1970. From this integer we can figure out a everything related to date and time. echo time( ); Let's look at another function getdate( ); <?php print_r (getdate()); ?> Array ( [seconds] => 38 [minutes] => 45 [hours] => 23 [mday] => 6 [wday] => 5 [mon] => 12 [year] => 2002 [yday] => 339 [weekday] => Friday [month] => December [0] => 1039236338 ) getdate( ) can be passed a time stamp for conversion into an array similiar to the one above. We can also reverse the process and create a timestamp out of a set of time and date values. <? Output: 1039277710 File System The following example illustrates how you can use PHP to access your file system. PHP can perform several useful file system related operations. <?php // set the directory I'd like to explore // This is my directory. $path = "/WWW"; // opendir()
returns a directory handle used in closedir(), readdir(), and rewinddir()
function calls. // readdir() reads an open directory handle while
($myfile = readdir($mydir)) { // This example will work fine without closing the directory handle. closedir($mydir); ?> Let's look at another example where we create a subdirectory using PHP. <?php // See
how simple it is to use PHP to create directories. Here you've create
a directory called $mynewfolder
= "phprules"; ?> Let's look at an example with a Date/Time function alongs with a File System Function. Let's say you wanted to know when the last time a particular file was accessed. <?php // First you specify a file for which the last access time needs to be procured. $myfile="test1.php"; print "The file $myfile was last accessed at: " . date( "D m/d/Y h:i:s a", fileatime("$myfile"))."<BR>"; print "The file $myfile was last modified at: " . date( "D m/d/Y h:i:s a", filemtime("$myfile"))."<BR>"; ?> Output: The file
test1.php was last accessed at: Sun 12/08/2002 12:11:07 am
|
© 2003 Ranjan Chari