//2011-11-27 星期日
//正则实战(2):
Preg_match验证URL
$subscr=$_REQUEST['subscr'];
//url validation
if (preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $subscr))
{
print "$subscr url OK.";
} else {
print "$subscr url not valid!";
}
//echo("$subscr");
?>
用ereg进行邮箱验证:
function validateMail($mail) {
if($mail !== "") {
if(ereg("^[-A-Za-z0-9_]+[-A-Za-z0-9_.]*[@]{1}[-A-Za-z0-9_]+[-A-Za-z0-9_.]*[.]{1}[A-Za-z]{2,5}$", $mail)) {
return true;
} else {
return false;
}
} else {
return false;
}
}
?>
IP地址匹配验证:
function validateIpAddress($ip_addr)
{
//first of all the format of the ip address is matched
if(preg_match("/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/",$ip_addr))
{
//now all the intger values are separated
$parts=explode(".",$ip_addr);
//now we need to check each part can range from 0-255
foreach($parts as $ip_parts)
{
if(intval($ip_parts)>255 || intval($ip_parts)<0)
return false; //if number is not within range of 0-255
}
return true;
}
else
return false;
}
UK 邮编验证: www.2cto.com
function IsPostcode($postcode) {
$postcode = strtoupper($postcode);
if(ereg("((GIR 0AA)|(TDCU 1ZZ)|(ASCN 1ZZ)|(BIQQ 1ZZ)|(BBND 1ZZ)"
."|(FIQQ 1ZZ)|(PCRN 1ZZ)|(STHL 1ZZ)|(SIQQ 1ZZ)|(TKCA 1ZZ)"
."|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]"
."|[A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y]))"
."|[0-9][A-HJKS-UW]) [0-9][ABD-HJLNP-UW-Z]{2})", $postcode)) {
return $postcode;
} else {
return FALSE;
}
}
?>
SSN 和邮编验证:
function isValid($type,$var) {
$valid = false;
switch ($type) {
case "IP":
if (ereg('^([0-9]{1,3}\.){3}[0-9]{1,3}$',$var)) {
$valid = true;
}
break;
case “URL”:
if (ereg("^[a-zA-Z0-9\-\.]+\.(com|org|net|mil|edu)$",$var)) {
$valid = true;
}
break;
case “SSN”:
if (ereg("^[0-9]{3}[- ][0-9]{2}[- ][0-9]{4}|[0-9]{9}$",$var)) {
$valid = true;
}
break;
case “CC”:
if (ereg("^([0-9]{4}[- ]){3}[0-9]{4}|[0-9]{16}$",$var)) {
$valid = true;
}
break;
case “ISBN”:
if (ereg("^[0-9]{9}[[0-9]|X|x]$",$var)) {
$valid = true;
}
break;
case “Date”:
if (ereg("^([0-9][0-2]|[0-9])\/([0-2][0-9]|3[01]|[0-9])\/[0-9]{4}|([0-9][0-2]|[0-9])-([0-2][0-9]|3[01]|[0-9])-[0-9]{4}$",$var)) {
$valid = true;
}
break;
case “Zip”:
if (ereg("^[0-9]{5}(-[0-9]{4})?$",$var)) {
$valid = true;
}
break;
case "Phone":
if (ereg("^((\([0-9]{3}\) ?)|([0-9]{3}-))?[0-9]{3}-[0-9]{4}$",$var)) {
$valid = true;
}
break;
case “HexColor”:
if (ereg('^#?([a-f]|[A-F]|[0-9]){3}(([a-f]|[A-F]|[0-9]){3})?$',$var)) {
$valid = true;
}
break;
case “User”:
if (ereg("^[a-zA-Z0-9_]{3,16}$",$var)) {
$valid = true;
}
break;
}
return $valid;
}
摘自 hi.baidu.com/micropoor