php面试基础知识--正则验证表单字段
2019-05-17 本文已影响0人
沙蒿同学
- 判断是否URL网址
<?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
- 0到1之间的1位小数
<?php
$float1 = 0.2;
$float2 = 0.12;
preg_match('/^0+(.[0-9]{1})?$/', $float1); // true
preg_match('/^0+(.[0-9]{1})?$/', $float2); // false
- 只含数字与英文,字符串长度并在4~16个字符
<?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
];
}