Article
Using Regular Expressions in PHP
Page: 1 2
Instead of the + sign we used before, here we have '{2,4}' immediately following the square brackets. This means that we require between 2 and 4 of the characters from the square brackets to be included in the email address. So com, net, org, uk, au, etc. are all valid, but anything longer than these will not be accepted.
Finally, the $ sign at the end of the expression signifies the end of the string. If we didn't include this, then a user could type anything after the end of the email address and it would still validate.
Here's the source code of a script you can use to test this regular expression -- and any others you want to play with:
<?php
if (!$_REQUEST['action']) {
?>
<form action='<?=$_SERVER['PHP_SELF']; ?>' method='POST'>
Email Address: <input type='text' name='email'>
<input type='hidden' name='action' value='validate'>
<p>
<input type='submit' value='Submit'>
</form>
<?php
}
if ($_REQUEST['action'] == 'validate') {
if (eregi('^[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.([a-zA-Z]{2,4})$',
$_REQUEST['email'])) {
echo 'Valid';
} else {
echo 'Invalid';
}
}
?>
Feel free to use the regular expression we made above on your own site to validate email addresses, or modify it for your own purposes.
Syntax Reference
This is a quick reference to some of the basic syntax. We've already seen much of it earlier on, but there are a few new things here that you may find useful.
^ start of string
$ end of string
[a-z] letters a-z inclusive in lower case
[A-Z] letters A-Z inclusive in upper case
[0-9] numbers 0-9 inclusive
[^0-9] no occurrences of numbers 0-9 inclusive
? zero or one of the preceding character(s)
* zero or more of preceding character(s)
+ one or more of preceding character(s)
{2} 2 of preceding character(s)
{2,} 2 or more of preceding character(s)
{2,4} 2 -- 4 of preceding character(s)
. any character
(a|b) a OR b
\s empty space (known as whitespace)