A regular expression is a simple programming language (for lack of a better term) which allows a programmer to search through text for a specific pattern.
For example, if I want to make sure a string contains a valid email address. I might need to match the following items in the string...
A regular expression to verify this might look something like:
"/[\w\.]{3,}@[\w\.]{1,}\.(net|com|org|edu)/"
PHP contains numerous functions to use with regular expressions which usually boil down to two groups of functions: ereg, and preg.
The differences between ereg and preg are very small and for this class we will be using the preg group of functions.
To check a string for a particular pattern in PHP, we can use the preg_match function.
$email = "REDACTED"; if(preg_match(\"/[\w\.]{3,}@[\w\.]{1,}\.(net|com|org|edu)/\",$email)) { print \"match\"; } else { print \"no match\"; }
We'll get into what this means later
As we see above, regular expressions can come in very handy for verifying data matches a certain pattern, however that is not the limit of regular expressions. We can use regular expressions to extract data from something.
For example, we could use a regular expression to get the information from a meta tag off an html document, or we could use a regular expression to rip through a log file on a web server and show us everytime a particular page was requested.
NEXT