$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 subexpres-
sion. The way we have written the regular expression is very exact. The
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>).
Handling HTML Forms
Given that PHP’s primary role is handling web pages, you might wonder why this section
has been left so late in the chapter. It is because handling HTML forms is so central to
PHP that it is essentially automatic.
Consider this form:
<form method=”POST” action=”thispage.php”>
User ID: <input type=”text” name=”UserID” /><br />
Password: <input type=”password” name=”Password” /><br />
<input type=”submit” />
When a visitor clicks Submit, thispage.php is called again and this time PHP has the vari-
ables 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 you 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 you to send a great deal
more data and stops people from tampering with your URL to try to find holes in your
Handling HTML Forms

Get Ubuntu Unleashed, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.