PHP allows for the use of two different types of Regular Expressions:
POSIX and Perl-compatible ones. Below are a few example scripts which
illustrate how to open a file in PHP, how to use Perl-compatible
regular expressions and how to use replacement and split/implode.
For the specific exercises, please, see the Perl version
of this page because the same exercises
can be used for Perl-compatible regular expressions in PHP.
Opening a file and printing it line by line
<html><head>
<title>Displaying a file line by line</title>
</head><body>
<hr><h1>Results:</h1><hr><p>
<?php
$lines = file('alice.txt');
foreach ($lines as $line_num => $line) {
echo "Line ",$line_num,": ",$line, "<br>\n";
}
?>
<p><hr></body></html>
Using regular expressions
<html><head>
<title>Searching</title> </head><body>
<hr><h1>Results:</h1><hr><p>
<?php
$lines = file('alice.txt');
foreach ($lines as $line_num => $line) {
if (preg_match("/the /i", $line, $matches)) {
echo "<br> Line ", $line_num, " matches: ",$matches[0],"<br>";
echo $line;
}
}
?>
<p><hr></body></html>
See here for details
on regular expressions and
here
for details and examples of preg_match.
Replacement
<html><head>
<title>Searching</title> </head><body>
<hr><h1>Results:</h1><hr><p>
<?php
$lines = file('alice.txt');
foreach ($lines as $line_num => $line) {
$line = preg_replace("/T/", 't', $line);
echo $line, "<br>";
}
?>
<p><hr></body></html>
See here
for details and examples of preg_replace.
Split and Implode
See here
for details and examples of preg_split.
See here
for details and examples of implode (which is the equivalent to Perl "join").