I’ve wrote a simple function to check if the string I send “should be” valid or not.
// this works without problems
function validate_email ($value) {
return preg_match ("/^[^0-9][A-z0-9_]+([.][A-z0-9_]+)*[@][A-z0-9_]+([.][A-z0-9_]+)*[.][A-z]{2,4}$/", $value);
}
// this doesn't work
function validate_string ($value) {
return preg_match ("([^<>?=/\]+)", $value);
}
the first function works well, if I send an email to validate_email I’m used to retain valid it return me 1 or 0 if not.
validate_string should do the same with strings of every kind but without ? = < > / \. If I check the function it return me 1 in anycase, why?
validate_string ("tonino"); // return 1 ok
validate_string ("ton\ino\"); // return 1 why?
validate_string ("ton?asd=3"); // return 1 why?
the ^ char inside ([^<>?=/]+) should mean not the chars after (or not?)
There are several errors in your code. Besides that
"ton\ino\"is not a valid string and[^<>?=/\]+is not a valid regular expression, you have probably some logical misunderstanding.Your regular expression
[^<>?=/\\]+(here corrected) will match if there is at least one character that is not<,>,?,=,/and\. So if there is at least one such character,preg_matchreturns1.ton\ino"andton?asd=3do both contain at least one such character (the match is in both caseston).A fix for this is to either use assertions for the start and end of the string (
^and$) to only allow legal characters for the whole string:Or to use a positive character class
[<>?=/\\]+to match the illegal characters and negate the returned expression ofpreg_match:But it would be certainly better to use a whitelist instead of a blacklist.