RegEx whitelist issue

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

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

Any idea why this is so?

+3
source share
4 answers

You have a typo in the pattern line that causes the problem

/ [^ a-zA- z 0-9_-]
Instead, you want A- Z .

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

+7
source

Adding to other answers.

[a-zA-Z0-9_] \w, char.

So [^a-zA-Z0-9_-] [^\w-]

+4

"z": "/[^ a-zA-Z0-9 _-]/"

+2
source

Do not take for granted what [a-zA-Z0-9_]coincides with \w. At http://se.php.net/manual/en/regexp.reference.escape.php it says that \w"may change if language matching is performed.

0
source

Source: https://habr.com/ru/post/1762273/


All Articles