views:

57

answers:

4

I'm a little confused. I am running all my inputs through a basic sanitize function I write to only allow certain characters, but characters such as [] are still being allowed.

function sanitize($input) {
$pattern = "/[^a-zA-z0-9_-]/";
$filtered = preg_replace($pattern, "", $input);
return $filtered;}

Any idea why it's doing that?

+7  A: 

You have a typo in your pattern string that's causing the problem

/[^a-zA-z0-9_-]
You want A-Z instead.


btw: you might be interested in the character class [:alnum:] and/or the PCRE_CASELESS modifier

VolkerK
+2  A: 

You have to capitalize the second "z": "/[^a-zA-Z0-9_-]/"

A. M.
+4  A: 

Adding to others answers.

[a-zA-Z0-9_] is same as \w, a word char.

So [^a-zA-Z0-9_-] can be written as [^\w-]

codaddict
darn, missed that =)
VolkerK
A: 

Don't take for granted that [a-zA-Z0-9_] is the same as \w, though. On http://se.php.net/manual/en/regexp.reference.escape.php it says that \w "may vary if locale-specific matching is taking place".

matsolof