最近在使用PHP的过程中,发现了一个特别好用的内置函数,用来验证输入数据的格式的,相对于自己写正则表达式来说,方便了不少,只要一个函数既可以搞定,我们来看一下:
要说的这个函数就是filter_var()
具体的用法如下:
如果您要验证某个字符是否是email:
filter_var($email, FILTER_VALIDATE_EMAIL)
具体的参考PHP手册:http://php.net/manual/zh/filter.filters.validate.php
而参考手册中有两种范例:sanitization和validation,两者的区别是什么呢?都有什么作用呢?
通过参考手册中的范例,如下示例
- sanitization
<?php
$a = 'joe@example.org';
$b = 'bogus - at - example dot org';
$c = '(bogus@example.org)';
$sanitized_a = filter_var($a, FILTER_SANITIZE_EMAIL);
if (filter_var($sanitized_a, FILTER_VALIDATE_EMAIL)) {
echo "This (a) sanitized email address is considered valid.\n";
}
$sanitized_b = filter_var($b, FILTER_SANITIZE_EMAIL);
if (filter_var($sanitized_b, FILTER_VALIDATE_EMAIL)) {
echo "This sanitized email address is considered valid.";
} else {
echo "This (b) sanitized email address is considered invalid.\n";
}
$sanitized_c = filter_var($c, FILTER_SANITIZE_EMAIL);
if (filter_var($sanitized_c, FILTER_VALIDATE_EMAIL)) {
echo "This (c) sanitized email address is considered valid.\n";
echo "Before: $c\n";
echo "After: $sanitized_c\n";
}
?>
- validatioin
<?php
$email_a = 'joe@example.com';
$email_b = 'bogus';
if (filter_var($email_a, FILTER_VALIDATE_EMAIL)) {
echo "Email address '$email_a' is considered valid.\n";
}
if (filter_var($email_b, FILTER_VALIDATE_EMAIL)) {
echo "Email address '$email_b' is considered valid.\n";
} else {
echo "Email address '$email_b' is considered invalid.\n";
}
?>
以上代码不难发现,sanitization是将需要验证的字符串进行处理之后,提取里面更符合标准的字符串,而validate验证方法呢,则是直接将需要验证的字符串进行完整匹配。