The quantifiers are metacharacters that allow you to dictate how many times something can or must appear. They are greedy, i.e. they match as much as they can.
| Character | Meaning |
|---|---|
| ? | 0 or 1 |
| * | 0 or more |
| + | 1 or more |
| {x} | Exactly x occurences |
| {x, y} | Between x and y (inclusive) |
| {x,} | At least x occurences |
<html>
<head>
<title>PHP</title>
<meta Name="Author" Content="Hann So">
</head>
<body>
<p>
<?php
if (isset($_POST['submit'])) {
process_form();
}
else {
display_form();// display form for the first time
}
function display_form() {
echo <<<HTML
<form action = "$_SERVER[SCRIPT_NAME]" method="post">
Regular Expression Pattern (include the delimiter):<br />
<input type="text" name="pattern" value="/w.+d/" /><br />
Text:<br />
<input type="text" name="text" size="70"
value="Welcome to the world of PHP. The Internet world is full of challenges." /><br />
<input type="submit" name="submit" value="Check" />
</form>
<table border>
<tr bgcolor="lightcyan">
<th align="left">Regular Expression</th>
<th align="left">Text</th>
</tr>
<tr>
<td>/c.+t/
<br />(contains the letters c and t, with one or more letetrs in between)
</td>
<td>cool, I like carrots.
</td>
</tr>
<tr bgcolor="lightyellow">
<td>/^carrots?$/
<br />(for exact match, use ^ and $.)
</td>
<td>cool, I eat a carrot a day. I like carrots.
</td>
</tr>
</table>
HTML;
}
function process_form() {
// trim the strings
$pattern = trim($_POST['pattern']);
$text = trim($_POST['text']);
echo "The result of checking <br /><font color=red>$pattern</font><br />
against<br /><font color=red>$text</font><br /> is:<br />";
// match the pattern
if (preg_match($pattern, $text, $matches)) {
echo "$pattern was matched. <br />";
}
else {
echo "$pattern was not matched. <br />";
}
echo "<br />The matches array contains:<br />";
foreach ($matches as $key =>$values) {
echo $key, " => ", $values, "<br />";
}
echo "<br /><a href=\"$_SERVER[SCRIPT_NAME]\">Check again?</a>";
}
?>
</p>
</body>
</html>
|