Validation

Example #1 Validating email addresses with filter_var()

<?php
$email_a 
'joe@example.com';
$email_b 'bogus';

if (
filter_var($email_aFILTER_VALIDATE_EMAIL)) {
    echo 
"Email address '$email_a' is considered valid.\n";
}
if (
filter_var($email_bFILTER_VALIDATE_EMAIL)) {
    echo 
"Email address '$email_b' is considered valid.\n";
} else {
    echo 
"Email address '$email_b' is considered invalid.\n";
}
?>

以上例程会输出:

Email address 'joe@example.com' is considered valid.
Email address 'bogus' is considered invalid.

Example #2 Validating IP addresses with filter_var()

<?php
$ip_a 
'127.0.0.1';
$ip_b '42.42';

if (
filter_var($ip_aFILTER_VALIDATE_IP)) {
    echo 
"IP address '$ip_a' is considered valid.";
}
if (
filter_var($ip_bFILTER_VALIDATE_IP)) {
    echo 
"IP address '$ip_b' is considered valid.";
}
?>

以上例程会输出:

IP address '127.0.0.1' is considered valid.

Example #3 Passing options to filter_var()

<?php
$int_a 
'1';
$int_b '-1';
$int_c '4';
$options = array(
    
'options' => array(
        
'min_range' => 0,
        
'max_range' => 3,
    )
);
if (
filter_var($int_aFILTER_VALIDATE_INT$options) !== FALSE) {
    echo 
"Integer A '$int_a' is considered valid (between 0 and 3).\n";
}
if (
filter_var($int_bFILTER_VALIDATE_INT$options) !== FALSE) {
    echo 
"Integer B '$int_b' is considered valid (between 0 and 3).\n";
}
if (
filter_var($int_cFILTER_VALIDATE_INT$options) !== FALSE) {
    echo 
"Integer C '$int_c' is considered valid (between 0 and 3).\n";
}

$options['options']['default'] = 1;
if ((
$int_c filter_var($int_cFILTER_VALIDATE_INT$options)) !== FALSE) {
    echo 
"Integer C '$int_c' is considered valid (between 0 and 3).";
}
?>

以上例程会输出:

Integer A '1' is considered valid (between 0 and 3).
Integer C '1' is considered valid (between 0 and 3).

User Contributed Notes

nora@nora 20-Mar-2021 09:26
this function gives true to nora@nora  when ther is no "extension" .com
dows 04-May-2018 08:26
It considers umlauts-domains as invalid.

test@t?st.de -> false
t?st@test.de -> false
Anonymous 21-Nov-2017 07:34
the problem listed before with the e-mail address: gnix@lineone.netsteve.gynes@lane4.co.uk being flagged as valid seems to not be a problem anymore, at least not on 5.6.30
PHP8中文手册 站长在线 整理 版权归PHP文档组所有