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