php url,日期,ip,邮箱地址检测类代码

本文章提供的确款正则表达式来检测url地址,日期格式,ip地址,与邮箱地址是否合法的验证代码,希望本文章对各位同学会带来帮助,代码如下:

  1. class validation{
  2. function check_email($value){ //check a email address
  3. return (bool) preg_match('/^[a-z0-9._%+-]+@(?:[a-z0-9-]+.)+[a-z]{2,4}$/i', $value);
  4. }
  5. function check_ip($value){ //check a ip address
  6. return (bool) preg_match("/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){4}$/", $value.".");
  7. }
  8. function check_date($date, $format="dd/mm/yy"){ //check a date
  9. if(!preg_match("/([0-9]+)([./-])([0-9]+)(\2)([0-9]+)/", $date, $m)) return false;
  10. $f = explode("/", $format);
  11. $d[$f[0]] = $m[1];
  12. $d[$f[1]] = $m[3];
  13. $d[$f[2]] = $m[5];
  14. return checkdate($d['mm'], $d['dd'], $d['yyyy'].$d['yy']);
  15. }
  16. function check_url($url){ //check a url
  17. return (bool) preg_match("/^(?:(?:ht|f)tp(?:s?)://|~/|/)?(?:(?:w+.)+)w+(?::d+)?(?:(?:/[^/?#]+)+)?/?(?:?[^?]*)?(#.*)?$/i", $url);
  18. }
  19. }

调用方法,代码如下:

  1. $validation = new validation();
  2. //检测邮箱:
  3. var_dump($validation->check_email("abc@abc.abc.com"));//true
  4. var_dump($validation->check_email("abc.abc@abc.com"));//false
  5. //ip检测:
  6. var_dump($validation->check_ip("127.0.0.1.0"));
  7. var_dump($validation->check_ip("256.0.0.1"));
  8. //日期格式检测:
  9. //true
  10. var_dump($validation->check_date("2010/1/20", "yyyy/mm/dd"));
  11. var_dump($validation->check_date("1/20/10", "mm/dd/yy"));
  12. var_dump($validation->check_date("2010-20-1", "yyyy/dd/mm"));
  13. //false
  14. var_dump($validation->check_date("2010/2/29", "yyyy/mm/dd"));//开源代码phpfensi.com
  15. var_dump($validation->check_date("2010/1/20", "yyyy/dd/mm"));
  16. var_dump($validation->check_date("2010-20/1", "yyyy/dd/mm"));

此类的使用方法非常简单吧,只要创建类就可以轻松的验证邮箱,日期,地址,ip是否为合法的的.