<p>我们最经常遇到的验证,就是电子邮件地址验证。网站上常见。各种网页脚本也都常用“正则表达式”(regular expression)对我们输入的电子邮件地址进行验证,判断是否合法。有的还能分解出用户名和域名。现在用PHP语言实现一下电子邮件地址验证程序,用的是PHP正则表达式库。</p>
<p>源代码如下:</p>
<p>复制代码<br />
<?php<br />
header ( "Content-Type: text/html; charset=UTF-8" );<br />
$reply = "";<br />
if ( isset($_POST["email_address"]) )<br />
{<br />
$email_address = $_POST["email_address"];<br />
$pattern = "/^([0-9A-Za-z\\-_\\.]+)@([0-9a-z]+\\.[a-z]{2,3}(\\.[a-z]{2})?)$/i";<br />
if ( preg_match( $pattern, $email_address ) )<br />
{<br />
$reply = "您输入的电子邮件地址合法<br /><br />\n";<br />
$user_name = preg_replace( $pattern ,"$1", $email_address );<br />
$domain_name = preg_replace( $pattern ,"$2", $email_address );<br />
$reply .= "用户名:".$user_name."<br />\n";<br />
$reply .= "域名:".$domain_name."<br />\n\n";<br />
}<br />
else<br />
{<br />
$reply = "您输入的电子邮件地址不合法";<br />
}<br />
}<br />
?><br />
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><br />
<html xmlns="http://www.w3.org/1999/xhtml" lang="zh" xml:lang="zh"><br />
<head><br />
<title>电子邮件地址验证程序</title><br />
</head><br />
<body style="text-align: center;"><br />
<h1>电子邮件地址验证程序</h1><br />
<form action="#" method="post"><br />
请输入电子邮件地址:<input name="email_address" type="text" style="width: 300px;" /><br /><br />
<input type="submit" value="验证电子邮件地址" /><br />
</form><br />
<?php<br />
echo $reply;<br />
?><br />
</body><br />
</html></p>