清理mysql搜索字符串的函数(主要是删除通配符)?
是否有内置的 php(或 MySQL)函数可以清理搜索中使用的字符串?在本例中,我只想在将字符串字母表(大写字母和小写字母)传递到 MySQL 正则表达式之前创建它。
我使用 PDO 和参数化查询,所以我不担心 SQL 注入。但是,我想确保有人不会传入通配符并占用太多内存。到目前为止,这就是我用来删除除空格和字母表之外的所有内容的方法。这够了吗?
preg_replace("/[^A-Za-z\s\s+]/", "", $query);
Is there a built-in php (or MySQL) function that will sanitise a string to be used in a search? In this case, I want to make a string alphabet (upper and lower) only, before it's passed into a MySQL regex.
I'm using PDO and parameterized queries, so I'm not worried about SQL injection. However, I want to make sure someone doesn't pass in wildcards and use up too much memory. So far, this is what I'm using to remove everything but spaces and the alphabet. Is this enough?
preg_replace("/[^A-Za-z\s\s+]/", "", $query);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为什么不简单地删除
%
和?
?这些是从记忆角度来看很重要的通配符。从长远来看,这将为您提供最大的可扩展性,而不会为后来的开发人员引入另一种WTF??!
潜力?就此而言,您可以通过避免
LIKE
来完全回避该问题,但这可能是不可能的。如果您必须比这更有选择性,那么我会排除所有
[^\w\s]+
。您不想排除数字,并且允许-
和_
没有什么坏处。Why not simply removed
%
and?
? Those are the wildcards which will matter from a memory perspective. That will afford you the most extensibility in the long run without introducing another potential for aWTF??!
by a later developer?For that matter, you can side-step the issue entirely by avoiding
LIKE
, but that might not be possible.If you must be more selective than that, then I would exclude all
[^\w\s]+
. You don't want to exclude numbers, and there is little harm in allowing-
and_
.您拥有的正则表达式将删除的不仅仅是您担心的通配符,所以我认为这不是最好的解决方案。 (你无疑听说过这个引用,但无论如何我都会重复一遍。)
有内置的 PHP 函数可以帮助您进行过滤。看看使用 filter_var() 与 PHP 的清理过滤器,如果您想做清理 URL 或电子邮件之类的事情,
但是,就您的情况而言,我认为以下是最简单的。
The regular expression you have will strip more than just the wildcards you are worried about, so I don't think it's the best solution. (You've undoubtedly heard this quote, but I'll repeat it anyhow.)
There are built-in PHP functions that can help you with filtering. Take a look at using filter_var() in combination with PHP's sanitize filters, if you want to do something like sanitize a URL or e-mail.
However, in your case, I think the following is simplest.