php正则表达式验证Email地址的例子

发布时间:2020-06-18编辑:脚本学堂
本文介绍下,在php中借助正则表达式来验证Email邮箱地址的例子,有需要的朋友参考下。

php实现验证邮箱地址的例子,很好的应用了php的正则。

1,html部分

<HTML>
<BODY>
<H2>php正则验证Email地址</H2>
<FORM METHOD="POST" ACTION="RegularExpressionTester.php">
<FONT FACE="Courier">
String:
<BR>
<INPUT TYPE="TEXT" NAME="string">
<BR><BR>
正则表达式:
<BR>
<INPUT TYPE="TEXT" SIZE=64 NAME="pattern" 
       VALUE="^([_a-zA-Z0-9-]+)@([a-zA-Z0-9-]+(.[a-zA-Z0-9-]+)*)$">
<BR><BR>
<BR>
<INPUT TYPE="SUBMIT">
</FONT>
</FORM>
</BODY>
</HTML>

2,php代码部分 RegularExpressionTester.php

<?php
echo "<BR><B>string:</B>$string";
echo "<BR><B>regular expression:</B>&nbsp;$pattern";
if (get_magic_quotes_gpc()){
    echo "<BR><BR>";
    echo "<BR>Stripping magic quotes....";
    $string = stripslashes($string);
    $pattern = stripslashes($pattern);
    echo "<BR><B>string:</B>&nbsp;$string";
    echo "<BR><B>regular expression:</B>&nbsp;$pattern";
}
$found = ereg($pattern, $string, $matches);
echo "<BR><BR>";
if ($found)
{
    echo "<BR><B>验证:</B>&nbsp;成功";
    echo "<BR><BR>";
    echo "<BR><B>Components:&nbsp</B>";
    for ($i = 0; $i < count($matches); $i++)
    {
        echo "<BR>$matches[$i]";
    }
}
else
    echo "<BR><B>验证:</B>&nbsp;失败";
?>