本文章提供的确款正则表达式来检测url地址,日期格式,ip地址,与邮箱地址是否合法的验证代码,希望本文章对各位同学会带来帮助,代码如下:
- class validation{
- function check_email($value){ //check a email address
- return (bool) preg_match('/^[a-z0-9._%+-]+@(?:[a-z0-9-]+.)+[a-z]{2,4}$/i', $value);
- }
- function check_ip($value){ //check a ip address
- return (bool) preg_match("/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){4}$/", $value.".");
- }
- function check_date($date, $format="dd/mm/yy"){ //check a date
- if(!preg_match("/([0-9]+)([./-])([0-9]+)(/2)([0-9]+)/", $date, $m)) return false;
- $f = explode("/", $format);
- $d[$f[0]] = $m[1];
- $d[$f[1]] = $m[3];
- $d[$f[2]] = $m[5];
- return checkdate($d['mm'], $d['dd'], $d['yyyy'].$d['yy']);
- }
- function check_url($url){ //check a url
- return (bool) preg_match("/^(?:(?:ht|f)tp(?:s?)://|~/|/)?(?:(?:w+.)+)w+(?::d+)?(?:(?:/[^/?#]+)+)?/?(?:?[^?]*)?(#.*)?$/i", $url);
- }
- }
调用方法,代码如下:
- $validation = new validation();
- //检测邮箱:
- var_dump($validation->check_email("abc@abc.abc.com"));//true
- var_dump($validation->check_email("abc.abc@abc.com"));//false
- //ip检测:
- var_dump($validation->check_ip("127.0.0.1.0"));
- var_dump($validation->check_ip("256.0.0.1"));
- //日期格式检测:
- //true
- var_dump($validation->check_date("2010/1/20", "yyyy/mm/dd"));
- var_dump($validation->check_date("1/20/10", "mm/dd/yy"));
- var_dump($validation->check_date("2010-20-1", "yyyy/dd/mm"));
- //false
- var_dump($validation->check_date("2010/2/29", "yyyy/mm/dd"));//开源代码Vevb.com
- var_dump($validation->check_date("2010/1/20", "yyyy/dd/mm"));
- var_dump($validation->check_date("2010-20/1", "yyyy/dd/mm"));
此类的使用方法非常简单吧,只要创建类就可以轻松的验证邮箱,日期,地址,ip是否为合法的的.
新闻热点
疑难解答