正则表达式白名单问题
我有点困惑。我通过我编写的基本清理函数运行所有输入,只允许某些字符,但仍然允许使用诸如 []
之类的字符。
function sanitize($input) {
$pattern = "/[^a-zA-z0-9_-]/";
$filtered = preg_replace($pattern, "", $input);
return $filtered;}
知道为什么要这样做吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您的模式字符串中有一个拼写错误,导致了问题
You want A-Z instead.
:您可能对字符类 [:alnum:] 和/或 PCRE_CASELESS 修饰符
You have a typo in your pattern string that's causing the problem
You want A-Z instead.
btw: you might be interested in the character class [:alnum:] and/or the PCRE_CASELESS modifier
添加到其他人的答案。
[a-zA-Z0-9_]
与\w
相同,一个单词字符。所以
[^a-zA-Z0-9_-]
可以写成[^\w-]
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-]
您必须将第二个“z”大写:“/[^a-zA-Z0-9_-]/”
You have to capitalize the second "z": "/[^a-zA-Z0-9_-]/"
不过,不要想当然地认为
[a-zA-Z0-9_]
与\w
相同。在 http://se.php.net/manual/en/regexp .reference.escape.php 它表示\w
“如果发生特定于区域设置的匹配,则可能会有所不同”。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".