Ubuntu Unleashed 2019 Edition: Covering 18.04, 18.10, 19.04

(singke) #1
        $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 the back reference; 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 back referenced in the
replacement is removed, so you 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:


Click here to view code image
File_get_contents() (manual) is easier than using fopen()
(manual).


Handling HTML Forms


Given that PHP’s primary role is handling web pages, you might wonder why
this section has been left until so late in the chapter. It is because handling
HTML forms is so central to PHP that it is essentially automatic.


Consider this form:


Click here to view code image



User ID:

Password:



When a visitor clicks Submit, thispage.php is called again, and this time
PHP has the variables available to it inside the $_REQUEST array. Given that
script, if the user enters 12345 and frosties as her user ID and password,
PHP provides with $_REQUEST[‘UserID’] set to 12345 and
$_REQUEST[‘Password’] set to frosties. Note that it is important
that you use HTTP POST unless you specifically want GET. POST enables

Free download pdf