Mastering Regular Expressions in PHP
(Page 2 out of 4)What would a good tutorial be without some real examples? Let's first have a look at a simple e-mail validation function. An e-mail address must start with letters or numbers, then have a @, then a domain, ending with an extension. The regex for that would be something like this: ^[a-zA-Z0-9_\.\-]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$
Let me quickly explain that regex. Basically, the first part says that it must all be letters or numbers. Then we get the @, and after that there should be letters and/or numbers again (the domain). Finally we check for a period, and then for an extension. The code to use this regex looks like this:
// Good e-mail
$good = "[email protected]";
// Bad e-mail
$bad = "blabla@blabla";
// Let's check the good e-mail
if (preg_match("/^[a-zA-Z0-9_\.\-]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$/", $good)) {
echo "Valid e-mail";
} else {
echo "Invalid e-mail";
}
echo '';
// And check the bad e-mail
if (preg_match("/^[a-zA-Z0-9_\.\-]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$/", $bad)) {
echo "Valid e-mail";
} else {
echo "Invalid e-mail";
}
?>
The result of this would be "Valid E-mail. Invalid E-mail", of course. We have just checked if an e-mail address is valid. If you wrap the above code in a function, you've got yourself a e-mail validation function. Keep in mind though that the regex isn't perfect: after all, it doesn't check whether the extension is too long, does it? Because I want to keep this tutorial short, I won't give the full fledged regex, but you can find it easily via Google.