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
Run Code Online (Sandbox Code Playgroud)
Kim*_*ble 10
它是用于存储有关人员信息的数据类.它还会对电子邮件进行验证.如果您为set_email方法提供了无效的电子邮件(在这种情况下是与正则表达式不匹配的字符串),则该方法将返回false.
这是一个存储用户名和电子邮件地址的类.set_email()方法检查提供的地址,以确保它在存储之前看起来有效.
该eregi函数检查使用正则表达式的电子邮件地址.这些是执行字符串操作和解析的非常强大的方法,但该特定示例可能不是最佳介绍.如果您刚开始使用正则表达式,您可能希望查看Perl兼容的正则表达式,因为它们使用得更广泛且功能更强大.此外,ereg函数将从PHP5.3 +弃用
这是介绍性信息的一个来源,我建议使用像Regex Coach这样的应用来玩和测试正则表达式.
要打破它:
^ # 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
Run Code Online (Sandbox Code Playgroud)
编写正则表达式以匹配所有有效电子邮件地址的100%是相当复杂的,这是一个与大多数匹配的简化模式.这是一篇关于编写电子邮件地址正则表达式模式的好文章.