一 代码
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <Meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <title>使用preg_match()函数和preg_match_all()函数验证手机和座机号码的格式是否正确</title> </head> <body> <?PHP $checktel="/^(\d{3}-)(\d{8})$|^(\d{4}-)(\d{7})$|^(\d{4}-)(\d{8})$/"; //定义验证座机号码的正则表达式 $checkphone="/^13(\d{9})$|^15(\d{9})$/"; //定义验证手机号码的正则表达式 if($_POST[check_tel]!="" and $_POST[Submit]=="提交"){ //判断是否有数据提交 if(preg_match($checktel,$_POST[check_tel],$counts)){ //执行验证操作 echo "<script>alert('电话号码格式正确!');window.location.href='index.PHP';</script>"; }else{ echo "<script>alert('电话号码格式不正确!');window.location.href='index.PHP';</script>"; } } if($_POST[check_phone]!="" and $_POST[Submites]=="提交"){ if(preg_match_all($checkphone,$_POST[check_phone],$counts)){ echo "<script>alert('手机号码格式正确!');window.location.href='index.PHP';</script>"; }else{ echo "<script>alert('手机号码格式不正确!');window.location.href='index.PHP';</script>"; } } ?> <table width="851" height="483" border="0" align="center" cellpadding="0" cellspacing="0" background="images/bg.jpg"> <tr> <td height="119" colspan="3"> </td> </tr> <tr> <td width="336" height="264"> </td> <td width="451" align="center" valign="top"><table width="381" height="175" border="0" cellpadding="0" cellspacing="0"> <tr> <td colspan="3" align="center">preg_match()和preg_match_all()函数的应用</td> </tr><form id="form1" name="form1" method="post" action="index.PHP"> <tr> <td width="88">座机号码:</td> <td width="223"><input type="text" name="check_tel" /></td> <td width="70"><input type="submit" name="Submit" value="提交" /></td> </tr> <tr> <td width="88">手机号码:</td> <td width="223"><input type="text" name="check_phone" /></td> <td width="70"><input type="submit" name="Submites" value="提交" /></td> </tr> </form> <tr> <td> </td> <td> </td> <td> </td> </tr> </table></td> <td width="64" valign="top"> </td> </tr> <tr> <td height="100"> </td> <td> </td> <td> </td> </tr> </table> </body> </html>
二 运行效果
输入:234-54345675
输出:电话号码格式正确