Metracharacters are special symbols that have a meaning beyond their literal value. They allow you to control the search pattern in some way (e.g., finding a pattern only at the beginning of the line). They will lose their special meaning if preceded with a backslash.
Character | Meaning |
---|---|
\ | Escape character |
^ | Indicates the beginning of a string |
$ | Indicates the end of a string |
. | Any single character except newline |
| | Alternatives (or) |
[ | Start of a v |
] | End of a class |
( | Start of a subpattern |
) | End of a subpattern |
{ | Start of a quantifier |
} | End of a quantifier |
The first type of character you will use for defining a pattern is literal. A literal is a value that is written excatly as it is interpreted. Along with literals, your patterns will use metacharacters. The most important of which are the caret (^) and the dollar sign ($).
<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="/^world/" /><br /> Text:<br /> <textarea name="text" rows="5" cols="50"> Welcome to the world of PHP. The Internet world is full of challenges. </textarea><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>/^... / <br />(Go to the beginning (^) of the line and find any 3 characters, followed by a space.) </td> <td>red apple 0.50 green apple 0.45 fuji apple 0.65 </td> </tr> </table> HTML; } function process_form() { // stripslashes and trim the strings $pattern = stripslashes(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> |