正则表达式验证IP地址

一 代码

<!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>应用正则表达中的点字符(.)</title>
<style type="text/css">
<!--
body {
	margin-left: 0px;
	margin-top: 0px;
	margin-right: 0px;
	margin-bottom: 0px;
}
-->
</style></head>
<body>
<?php 
$checkip="/^(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])(\.)(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])(\.)(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])(\.)(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])$/";
if($_POST[check_ip]!="" and $_POST[Submit]=="提交"){
	if(preg_match($checkip,$_POST[check_ip],$counts)){
		echo "<script>alert('IP地址格式正确!');window.location.href='index.php';</script>"; 	
	}else{
		echo "<script>alert('IP地址格式不正确!');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">&nbsp;</td>
  </tr><form id="form1" name="form1" method="post" action="index.php">
  <tr>
    <td width="336" height="264">&nbsp;</td>
    <td width="260" align="center" valign="top">IP地址:
      <input type="text" name="check_ip" /></td>
    <td width="255" valign="top"><input type="submit" name="Submit" value="提交" /></td>
  </tr></form>
  <tr>
    <td height="100">&nbsp;</td>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
  </tr>
</table>
</body>
</html>
二 运行结果
输入:56.06.45.33
输出:IP地址格式不正确

猜你喜欢

转载自cakin24.iteye.com/blog/2351543