Leandro Garcia
Leandro Garcia

Reputation: 3228

negate special characters

I used preg_match() to blacklist some special characters, my requirement is whenever the string contains such special characters, I would return an invalid.

$str = "adasdasasd*";
if(preg_match('/^[^~`!@#$%\^&\*\(\)]+$/',$str)) {
  echo "valid";
}
else {
  echo "invalid";
}

This returns invalid, which is correct. However, up until now I'm quite confused with this negate on preg_match. Can someone have at least a brief explanation of negate on preg_match()? And also, is the regular expression I provided to preg_match() has any downside?

Upvotes: 1

Views: 289

Answers (1)

slugonamission
slugonamission

Reputation: 9642

Ok, so your regular expression contains a range specifier, in this case, [^~!@#$%\^&\*\(\)]+. That's a little complex, so let's simplify for now to [abc].

[abc] will match any letter which is a, b or c, as you probably know. Adding in a ^ first negates this set, so [^abc] matches any letter that is not a, b or c, so will match d, e, f, g, H, 4, £ and so on.

In your case, you are matching anything that is not in your list of special characters. You're saying "match start of string, then match one or more 'non-special' characters, then match the end of the string". If you have any special characters, they cannot be matched by the "non-special" character match, or anything else, thus the regex fails.

Upvotes: 2

Related Questions