电子邮件地址特殊字符混淆

I was playing around with filter_var to validate emails:

$email = "test@test.com"; 

if( filter_var( $email, FILTER_VALIDATE_EMAIL ) ){

    echo "{Valid Email";

}else{

    echo "Invalid Email";

}

That returns Valid Email.

But when I tried special characters like . $ # * ? & ! ^ ~ / ' - _ @ % {} | = + at the local part, Like :

$email = "te?st@test.com";
$email = "te/st@test.com";
$email = "te'st@test.com";
$email = "te}st@test.com";
$email = "te|st@test.com";
$email = "te=st@test.com";

That would return Valid Email too.

It's not accepting characters like <> [] ,.

But if I use $:

$email = "te$st@test.com";

That would return Valid Email, But also NOTICE Undefined variable: st

So should I use it to validate email addresses, Before inserting them to the DB?

Or I should use a custom Regular Expression?

When using double quoted strings, the $ character is seen as the beginning of a variable name. So $stlooks like a variable and PHP tries to interpolate it. This is easily resolved by using single quotes which does not interpolate variables in strings.

$email = 'te$st@test.com';

See the PHP documentation for strings to learn more about this as it is an important part of PHP development.