class person {
var $name;
var $email;
//Getters
function get_name() { return $this->name; }
function get_email() { return $this->email; }
//Setters
function set_name( $name ) { $this->name = $name; }
function set_email( $email ) {
if ( !eregi("^([0-9,a-z,A-Z]+)([.,_,-]([0-9,a-z,A-Z]+))*[@]([0-9,a-z,A-Z]+)([.,_,-]([0-9,a-z,A-Z]+))*[.]([0-9,a-z,A-Z]){2}([0-9,a-z,A-Z])*$", $email ) ) {
return false;
} else {
$this->email = $email;
return true;
}
}//EOM set_email
}//EOC person
views:
162answers:
2It's a data class for storing information about a person. It also does validation of emails. If you give the set_email method an invalid email (in this case a string that does not match the regex) the method will return false.
It's a class that stores a username and email address. The set_email() method checks the supplied address to ensure it looks valid before storing it.
The eregi function checks the email address using a regular expression. These are very powerful ways of perform string manipulation and parsing, but that particular example probably isn't the best introduction. If you're just getting started with using regular expressions, you might want to look at Perl compatible regular expressions as these are more widely used and are more powerful. In addition, the ereg functions will be deprecated from PHP5.3+
Here's one source of introductory information, and I'd recommend using an app like Regex Coach for playing around and testing regular expressions.
To break it down:
^ # force match to be at start of string
([0-9,a-z,A-Z]+) # one or more alphanumerics
([.,_,-]([0-9,a-z,A-Z]+)) # followed by period, underscore or
# dash, and more alphanumerics
* # last pattern can be repeated zero or more times
[@] # followed by an @ symbol
([0-9,a-z,A-Z]+) # and one or more alphanumerics
([.,_,-]([0-9,a-z,A-Z]+)) # followed by period, underscore or dash,
# and more alphanumerics
* # last pattern can be repeated zero or more times
[.] # followed by a period
([0-9,a-z,A-Z]){2} # exactly two alphanumerics
([0-9,a-z,A-Z])*$ # then the remainder of the string must be
# alphanumerics too - the $ matches the end of the
# string
Writing a regex to match 100% of all valid email addresses is rather complex, and this is a simplified pattern which will match a majority. Here's a good article on writing email address regex patterns.