Книга: Fedora™ Unleashed, 2008 edition

Miscellaneous

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 false — such as 0 or an empty string — still 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 27.5).

LISTING 27.5 Setting and Unsetting Variables

<?php
 $name = "Ildiko";
 if (isset($name)) {
  echo "Name was set to $namen";
  unset($name);
 } else {
  echo "Name was not set";
 }
 if (isset($name)) {
  echo "Name was set to $namen";
  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 you understand it:

<?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 often 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 differentiate 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 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 is that 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; that is, using the match as part of the replacement. For this example, imagine you have written a tutorial on PHP but want to process the text so that 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 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>).

Оглавление книги

Оглавление статьи/книги

Генерация: 0.658. Запросов К БД/Cache: 2 / 0
поделиться
Вверх Вниз