清理mysql搜索字符串的函数(主要是删除通配符)?

发布于 2024-11-29 21:11:18 字数 261 浏览 0 评论 0原文

是否有内置的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

┊风居住的梦幻卍 2024-12-06 21:11:18

为什么不简单地删除 %?这些是从记忆角度来看很重要的通配符。从长远来看,这将为您提供最大的可扩展性,而不会为后来的开发人员引入另一种 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 a WTF??! 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 _.

寻找一个思念的角度 2024-12-06 21:11:18

您拥有的正则表达式将删除的不仅仅是您担心的通配符,所以我认为这不是最好的解决方案。 (你无疑听说过这个引用,但无论如何我都会重复一遍。)

有些人在遇到问题时会想:“我知道,我会用
正则表达式。”

现在他们有两个问题。

有内置的 PHP 函数可以帮助您进行过滤。看看使用 filter_var()PHP 的清理过滤器,如果您想做清理 URL 或电子邮件之类的事情,

但是,就您的情况而言,我认为以下是最简单的。

// Are there any I missed?
$keys = array("?", "%");  
$sanitized = str_replace($keys, "", $query);

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.)

Some people, when confronted with a problem, think "I know, I'll use
regular expressions."

Now they have two problems.

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.

// Are there any I missed?
$keys = array("?", "%");  
$sanitized = str_replace($keys, "", $query);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文