PHP7编什么程

php面试基础知识--正则验证表单字段

2019-05-17  本文已影响0人  沙蒿同学
<?php
  $string = 'http://www.baidu.com';
  preg_match('#(http|https)://(.*\.)?.*\..*#i', $string);  // true
  //验证url地址内置函数
  filter_var($string, FILTER_VALIDATE_URL);  // true
<?php
  $string = '2288383@qq.com';
  preg_match("/^\\w+([-+.]\\w+)*@\\w*\\.\\w/", $string);  // true
  //验证邮箱内置函数
  filter_var($string, FILTER_VALIDATE_EMAIL);  // true
<?php
  $string = '13568659658';
  preg_match("/^1[345678]{1}\d{9}$/", $string);  // true
<?php
  $float1 = 0.2;
  $float2 = 0.12; 
  preg_match('/^0+(.[0-9]{1})?$/', $float1);  // true 
  preg_match('/^0+(.[0-9]{1})?$/', $float2);  // false
<?php
  $string = 'abc'; 
  preg_match("^[a-zA-Z0-9]{4,16}$", $string)  // false
<?php
  $string = '44528656556585454X'; 
  preg_match("\d{15}|\d{18}", $string)  //中国的身份证为15位或18位

后续会不断增加常见的表单验证字段的,也会考虑多种情况下的验证,大家可以也可以在下方留言,怎样封装才能更好的满足常见的验证。

<?php
  public function checkForm(string $string, string $type) : array
  {
        switch (strtolower($type)) {
          case 'email':
            $flag = preg_match('/^\\w+([-+.]\\w+)*@\\w*\\.\\w/', $string);
            $ret = $flag ? 'success' : '邮箱格式不正确';
              break;
          case 'url':
            $flag = preg_match('#(http|https)://(.*\.)?.*\..*#i', $string);
            $ret = $flag ? 'success' : 'URL地址格式不正确';
            break;
          case 'mobile':
            $flag = preg_match('/^1[345678]{1}\d{9}$/', $string);
            $ret = $flag ? 'success' : '手机号码格式不正确';
            break;
          case 'card':
            $flag = preg_match('\d{15}|\d{18}', $string);
            $ret = $flag ? 'success' : '身份证格式不正确';
            break;
          default:
            $flag = false;
            $ret = '参数不正确';
        }
        return [
          'code'  =>  $flag ? 0 : -1,
          'msg'   =>  $ret
        ];
  }
上一篇 下一篇

猜你喜欢

热点阅读