Basic Functions


PHP has a vast number of built-in functions that enable you to manipulate strings, connect to databases, and more. There is not room here to cover even 10% of the functions; for more detailed coverage of functions, check the "Reference" section at the end of this chapter.

Strings

Several important functions are used for working with strings, and there are many more less frequently used ones for which there is not enough space here. We are going to look at the most important here, ordered by difficultyeasiest first!

The easiest function is strlen(), which takes a string as its parameter and returns the number of characters in there, like this:

<?php   $ourstring = "  The Quick Brown Box Jumped Over The Lazy Dog  ";   echo strlen($ourstring); ?> 


We will be using that same string in subsequent examples to save space. If you execute that script, it outputs 48 because 48 characters are in the string. Note the 2 spaces on either side of the text, which pad the 44-character phrase up to 48 characters.

We can fix that padding with the TRim() function, which takes a string to trim and returns it with all the whitespace removed from either side. This is a commonly used function because all too often you encounter strings that have an extra new line at the end or a space at the beginning. This cleans it up perfectly.

Using TRim(), we can turn our 48-character string into a 44-character string (the same thing, without the extra spaces), like this:

echo trim($ourstring);


Keep in mind that trim() returns the trimmed string, so that outputs "The Quick Brown Box Jumped Over The Lazy Dog". We can modify that so trim() passes its return value to strlen() so that the code trims it and then outputs its trimmed length:

echo strlen(trim($ourstring));


PHP always executes the innermost functions first, so the previous code takes $ourstring, passes it through trim(), uses the return value of trim() as the parameter for strlen(), and prints it.

Of course, everyone knows that boxes do not jump over dogsthe usual phrase is "the quick brown fox." Fortunately, there is a function to fix that problem: str_replace(). Note that it has an underscore in it; PHP is inconsistent on this matter, so you really need to memorize the function name.

The str_replace() function takes three parameters: the text to search for, the text to replace it with, and the string you want to work with. When working with search functions, people often talk about needles and haystacksin this situation, the first parameter is the needle (the thing to find), and the third parameter is the haystack (what you are searching through).

So, we can fix our error and correct box to fox with this code:

echo str_replace("Box", "Fox", $ourstring);


There are two little addendums to make here. First, note that we have specified "Box" as opposed to "box" because that is how it appears in the text. The str_replace() function is a case-sensitive function, which means it does not consider "Box" to be the same as "box". If you want to do a non-case-sensitive search and replace, you can use the stri_replace() function, which works in the same way.

The second addendum is that, because we are actually changing only one character (B to F), we need not use a function at all. PHP enables you to read (and change) individual characters of a string by specifying the character position inside braces ({ and }). As with arrays, strings are zero based, which means in the $ourstring variable $ourstring{0} is T, $ourstring{1} is h, $ourstring{2} is e, and so on. We could use this instead of str_replace(), like this:

<?php   $ourstring = "  The Quick Brown Box Jumped Over The Lazy Dog  ";   $ourstring{18} = "F";   echo $ourstring; ?> 


You can extract part of a string using the substr() function, which takes a string as its first parameter, a start position as its second parameter, and an optional length as its third parameter. Optional parameters are common in PHP. If you do not provide them, PHP assumes a default value. In this case, if you specify only the first two parameters, PHP copies from the start position to the end of the string. If you specify the third parameter, PHP copies that many characters from the start.

We can write a simple script to print "Lazy Dog " by setting the start position to 38, which, remembering that PHP starts counting string positions from 0, copies from the 39th character to the end of the string:

echo substr($ourstring, 38);


If we just want to print the word "Lazy," we need to use the optional third parameter to specify the length as 4, like this:

echo substr($ourstring, 38, 4);


The substr() function can also be used with negative second and third parameters. If you specify just parameter one and two and provide a negative number for parameter two, substr() counts backward from the end of the string. So, rather than specifying 38 for the second parameter, we can use 10, so it takes the last 10 characters from the string. Using a negative second parameter and positive third parameter counts backward from the end string and then uses a forward length. We can print "Lazy" by counting 10 characters back from the end and then taking the next four characters forward:

echo substr($ourstring, -10, 4);


Finally, we can use a negative third parameter, too, which also counts back from the end of the string. For example, using "-4" as the third parameter means to take everything except the last four characters. Confused yet? This code example should make it clear:

echo substr($ourstring, -19, -11);


That counts 19 characters backward from the end of the string (which places it at the O in Over) and then copies everything from there until 11 characters before the end of the string. That prints "Over The". The same thing could be written using 19 and 8, or even 29 and 8there is more than one way to do it!

Moving on, the strpos() function returns the position of a particular substring inside a string; however, it is most commonly used to answer the question, "Does this string contain a specific substring?" You need to pass it two parameters: a haystack and a needle (yes, that's a different order from str_replace()!).

In its most basic use, strpos() can find the first instance of "Box" in our phrase, like this:

echo strpos($ourstring, "Box");


This outputs 18 because that is where the B in Box starts. If strpos() cannot find the substring in the parent string, it returns false rather than the position. Much more helpful, though, is the ability to check whether a string contains a substring; a first attempt to check whether our string contains the word The might look like this:

<?php   $ourstring = "The Quick Brown Box Jumped Over The Lazy Dog";   if (strpos($ourstring, "The")) {     echo "Found 'The'!\n";   } else {     echo "'The' not found!\n";   } ?> 


Note that we have temporarily taken out the leading and trailing whitespace from $ourstring and we are using the return value of strpos() for our conditional statement. This reads, "If the string is found, then print a message; if not, print another message." Or does it?

Run the script, and you will see it print the "not found" message. The reason for this is that strpos() returns false if the substring is not found and otherwise returns the position where it starts. If you recall, any nonzero number equates to true in PHP, which means that 0 equates to false. With that in mind, what is the string index of the first The in our phrase? Because PHP's strings are zero based and we no longer have the spaces on either side of the string, the The is at position 0, which our conditional statement evaluates to falsehence, the problem.

The solution here is to check for identicality. We know that 0 and false are equal, but they are not identical because 0 is an integer, whereas false is a Boolean. So, we need to rewrite the conditional statement to see whether the return value from strpos() is identical to false. If it is, the substring was not found:

<?php   $ourstring = "The Quick Brown Box Jumped Over The Lazy Dog";   if (strpos($ourstring, "The") !== false) {     echo "Found 'The'!\n";   } else {     echo "'The' not found!\n";   } ?> 


Arrays

Working with arrays is no easy task, but PHP makes it easier by providing a selection of functions that can sort, shuffle, intersect, and filter them. As with other functions, there is only space here to choose a selection; this is by no means a definitive reference to PHP's array functions.

The easiest function to use is array_unique(), which takes an array as its only parameter and returns the same array with all duplicate values removed. Also in the realm of "so easy you do not need a code example" is the shuffle() function, which takes an array as its parameter and randomizes the order of its elements. Note that shuffle() does not return the randomized array; it uses your parameter as a reference and scrambles it directly. The last too-easy-to-demonstrate function is in_array(), which takes a value as its first parameter and an array as its second and returns TRue if the value is in the array.

With those out of the way, we can focus on the more interesting functions, two of which are array_keys() and array_values(). They both take an array as their only parameter and return a new array made up of the keys in the array or the values of the array, respectively. The array_values() function is an easy way to create a new array of the same data, just without the keys. This is often used if you have numbered your array keys, deleted several elements, and want to reorder it.

The array_keys() function creates a new array where the values are the keys from the old array, like this:

<?php   $myarr = array("foo" => "red", "bar" => "blue", "baz" => "green");   $mykeys = array_keys($myarr);   foreach($mykeys as $key => $value) {     echo "$key = $value\n";   } ?> 


That prints "0 = foo", "1 = bar", and "2 = baz".

Several functions are used specifically for array sorting, but only two get much use: asort() and ksort(), the first of which sorts the array by its values and the second of which sorts the array by its keys. Given the array $myarr from the previous example, sorting by the values would produce an array with elements in the order bar/blue, baz/green, and foo/red. Sorting by key would give the elements in the order bar/blue, baz/green, and foo/red. As with the shuffle() function, both asort() and ksort() do their work in place, meaning they return no value, directly altering the parameter you pass in. For interest's sake, you can also use arsort() and krsort() for reverse value sorting and reverse key sorting, respectively.

This code example reverse sorts the array by value and then prints it as before:

<?php   $myarr = array("foo" => "red", "bar" => "blue", "baz" => "green");   arsort($myarr);   foreach($myarr as $key => $value) {     echo "$key = $value\n";   } ?> 


Previously when discussing constants, we mentioned the exTRact() function that converts an array into individual variables; now it is time to start using it for real. You need to provide three variables: the array you want to extract, how you want the variables prefixed, and the prefix you want used. Technically, the last two parameters are optional, but practically you should always use them to properly namespace your variables and keep them organized.

The second parameter must be one of the following:

  • EXTR_OVERWRITE If the variable exists already, overwrites it.

  • EXtr_SKIP If the variable exists already, skips it and moves on to the next variable.

  • EXTR_PREFIX_SAME If the variable exists already, uses the prefix specified in the third parameter.

  • EXtr_PREFIX_ALL Prefixes all variables with the prefix in the third parameter, regardless of whether it exists already.

  • EXtr_PREFIX_INVALID Uses a prefix only if the variable name would be invalid (for example, starting with a number).

  • EXtr_IF_EXISTS Extracts only variables that already exist. We have never seen this used.

You can also, optionally, use the bitwise OR operator, |, to add in EXtr_REFS to have exTRact() use references for the extracted variables. In general use, EXtr_PREFIX_ALL is preferred because it guarantees namespacing. EXTR_REFS is required only if you need to be able to change the variables and have those changes reflected in the array.

This next script uses extract() to convert $myarr into individual variables, $arr_foo, $arr_bar, and $arr_baz:

<?php   $myarr = array("foo" => "red", "bar" => "blue", "baz" => "green");   extract($myarr, EXTR_PREFIX_ALL, 'arr'); ?> 


Note that the array keys are "foo", "bar", and "baz" and that the prefix is "arr", but that the final variables will be $arr_foo, $arr_bar, and $arr_baz. PHP inserts an underscore between the prefix and array key.

Files

As you will have learned from elsewhere in the book, the UNIX philosophy is that everything is a file. In PHP, this is also the case: A selection of basic file functions is suitable for opening and manipulating files, but those same functions can also be used for opening and manipulating network sockets. We cover both here.

Two basic read and write functions for files make performing these basic operations easy. They are file_get_contents(), which takes a filename as its only parameter and returns the file's contents as a string, and file_put_contents(), which takes a filename as its first parameter and the data to write as its second parameter.

Using these two, we can write a script that reads all the text from one file, filea.txt, and writes it to another, fileb.txt:

<?php   $text = file_get_contents("filea.txt");   file_put_contents("fileb.txt", $text); ?> 


Because PHP enables us to treat network sockets like files, we can also use file_get_contents() to read text from a website, like this:

<?php   $text = file_get_contents("http://www.slashdot.org");   file_put_contents("fileb.txt", $text); ?> 


The problem with using file_get_contents() is that it loads the whole file into memory at once; that's not practical if you have large files or even smaller files being accessed by many users. An alternative is to load the file piece by piece, which can be accomplished through the following five functions: fopen(), fclose(), fread(), fwrite(), and feof(). The f in those function names stands for file, so they open, close, read from, and write to files and sockets. The last function, feof(), returns TRue if the end of the file has been reached.

The fopen() function takes a bit of learning to use properly, but on the surface it looks straightforward. Its first parameter is the filename you want to open, which is easy enough. However, the second parameter is where you specify how you want to work with the file, and you should specify one of the following:

  • r Read only; it overwrites the file

  • r+ Reading and writing; it overwrites the file

  • w Write only; it erases the existing contents and overwrites the file

  • w+ Reading and writing; it erases the existing content and overwrites the file

  • a Write only; it appends to the file

  • a+ Reading and writing; it appends to the file

  • x Write only, but only if the file does not exist

  • a+ Reading and writing, but only if the file does not exist

Optionally, you can also add b (for example, a+b or rb) to switch to binary mode. This is recommended if you want your scripts and the files they write to work smoothly on other platforms.

When you call fopen(), you should store the return value. It is a resource known as a file handle, which the other file functions all need to do their jobs. The fread() function, for example, takes the file handle as its first parameter and the number of bytes to read as its second, returning the content in its return value. The fclose() function takes the file handle as its only parameter and frees up the file.

So, we can write a simple loop to open a file, read it piece by piece, print the pieces, and then close the handle:

<?php   $file = fopen("filea.txt", "rb");   while (!feof($file)) {     $content = fread($file, 1024);     echo $content;   }   fclose($file); ?> 


That only leaves the fwrite() function, which takes the file handle as its first parameter and the string to write as its second. You can also provide an integer as the third parameter, specifying the number of bytes you want to write of the string, but if you exclude this, fwrite() writes the entire string.

If you recall, you can use a as the second parameter to fopen() to append data to a file. So, we can combine that with fwrite() to have a script that adds a line of text to a file each time it is executed:

<?php   $file = fopen("filea.txt", "ab");   fwrite($file, "Testing\n");   fclose($file); ?> 


To make that script a little more exciting, we can stir in a new function, filesize(), that takes a filename (not a file handle, but an actual filename string) as its only parameter and returns the file's size in bytes. Using that new function brings the script to this:

<?php   $file = fopen("filea.txt", "ab");   fwrite($file, "The filesize was" . filesize("filea.txt") . "\n");   fclose($file); ?> 


Although PHP automatically cleans up file handles for you, it is still best to use fclose() yourself so you are always in control.

Miscellaneous

Several functions do not fall under the other categories and so are covered here. The first one is isset(), which takes one or more variables as its parameters and returns true if they have been set. It is important to note that a variable with a value set to something that would be evaluated to falsesuch as 0 or an empty stringstill returns TRue from isset() because it does not check the value of the variable. It merely checks that it is set; hence, the name.

The unset() function also takes one or more variables as its parameters, simply deleting the variable and freeing up the memory. With these two, we can write a script that checks for the existence of a variable and, if it exists, deletes it (see Listing 29.5).

Listing 29.5. Setting and Unsetting Variables

<?php   $name = "Ildiko";   if (isset($name)) {     echo "Name was set to $name\n";     unset($name);   } else {     echo "Name was not set";   }   if (isset($name)) {     echo "Name was set to $name\n";     unset($name);   } else {     echo "Name was not set";   } ?> 

That script runs the same isset() check twice, but it unset()s the variable after the first check. As such, it prints "Name was set to Ildiko" and then "Name was not set".

Perhaps the most frequently used function in PHP is exit, although purists will tell you that it is in fact a language construct rather than a function. exit terminates the processing of the script as soon as it is executed, meaning subsequent lines of code are not executed. That is really all there is to it; it barely deserves an example, but here is one just to make sure:

<?php   exit;   echo "Exit is a language construct!\n"; ?> 


That script prints nothing because the exit comes before the echo.

One function we can guarantee you will use a lot is var_dump(), which dumps out information about a variable, including its value, to the screen. This is invaluable for arrays because it prints every value and, if one or more of the elements is an array, it prints all the elements from those, and so on. To use this function, just pass it a variable as its only parameter:

<?php   $drones = array("Graham", "Julian", "Nick", "Paul");   var_dump($drones); ?> 


The output from that script looks like this:

array(4) {   [0]=>   string(6) "Graham"   [1]=>   string(6) "Julian"   [2]=>   string(4) "Nick"   [3]=>   string(4) "Paul" } 


The var_dump() function sees a lot of use as a basic debugging technique because it is the easiest way to print variable data to the screen to verify it.

Finally, we briefly discuss regular expressions, with the emphasis on briefly because regular expression syntax is covered elsewhere in this book and the only unique thing relevant to PHP are the functions you will use to run the expressions. You have the choice of either Perl-Compatible Regular Expressions (PCRE) or POSIX Extended regular expressions, but there really is little to choose between them in terms of functionality offered. For this chapter, we use the PCRE expressions because, to the best of our knowledge, they see more use by other PHP programmers.

The main PCRE functions are preg_match(), preg_match_all(), preg_replace(), and preg_split(). We will start with preg_match() because it provides the most basic functionality by returning true if one string matches a regular expression. The first parameter to preg_match() is the regular expression you want to search for, and the second is the string to match. So, if we wanted to check whether a string had the word Best, Test, rest, zest, or any other word containing est preceded by any letter of either case, we could use this PHP code:

$result = preg_match("/[A-Za-z]est/", "This is a test");


Because the test string matches the expression, $result is set to 1 (TRue). If you change the string to a nonmatching result, you get 0 as the return value.

The next function is preg_match_all(), which gives you an array of all the matches it found. However, to be most useful, it takes the array to fill with matches as a by-reference parameter and saves its return value for the number of matches that were found.

We suggest you use preg_match_all() and var_dump() to get a feel for how the function works. This example is a good place to start:

<?php   $string = "This is the best test in the west";   $result = preg_match_all("/[A-Za-z]est/", $string, $matches);   var_dump($matches); ?> 


That outputs the following:

array(1) {   [0]=>   array(3) {     [0]=>     string(4) "best"     [1]=>     string(4) "test"     [2]=>     string(4) "west"   } } 


If you notice, the $matches array is actually multidimensional in that it contains one element, which itself is an array containing all the matches to our regular expression. The reason for this is because our expression has no subexpressions, meaning no independent matches using parentheses. If we had subexpressions, each would have its own element in the $matches array containing its own array of matches.

Moving on, preg_replace() is used to change all substrings that match a regular expression into something else. The basic manner of using this is quite easy: You search for something with a regular expression and provide a replacement for it. However, a more useful variant is backreferencing, using the match as part of the replacement. For our example, we will imagine you have written a tutorial on PHP but want to process the text so each reference to a function is followed by a link to the PHP manual.

PHP manual page URLs take the form http://www.php.net/<somefunc>for example, http://www.php.net/preg_replace. The string we need to match is a function name, which is a string of alphabetic characters, potentially also mixed with numbers and underscores and terminated with two parentheses, (). As a replacement, we will use the match we found, surrounded in HTML emphasis tags (<em></em>), and then with a link to the relevant PHP manual page. Here is how that looks in code:

<?php   $regex = "/([A-Za-z0-9_]*)\(\)/";   $replace = "<em>$1</em> (<a href=\"http://www.php.net/$1\">manual</A>)";   $haystack = "File_get_contents()is easier than using fopen().";   $result = preg_replace($regex, $replace, $haystack);   echo $result; ?> 


The $1 is our backreference; it will be substituted with the results from the first subexpression. The way we have written the regular expression is very exact. The [A-Za-z0-9_]* part, which matches the function name, is marked as a subexpression. After that is \(\), which means the exact symbols (and), not the regular expression meanings of them, which means that $1 in the replacement will contain fopen rather than fopen(), which is how it should be. Of course, anything that is not backreferenced in the replacement is removed, so we have to put the () after the first $1 (not in the hyperlink) to repair the function name.

After all that work, the output is perfect:

<em>File_get_contents()</em> (<a href="http://www.php.net/ file_get_contents">manual</A>) is easier than using <em>fopen() </em> (<a href="http://www.php.net/fopen">manual</A>). 




Ubuntu Unleashed
Ubuntu Unleashed 2011 Edition: Covering 10.10 and 11.04 (6th Edition)
ISBN: 0672333449
EAN: 2147483647
Year: 2006
Pages: 318

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net