简体   繁体   English

如何使用正则表达式返回带有MySQL查询的记录?

[英]How can I return records with a MySQL query using a regular expression?

I have records in my database that are searched with user input, and initially, this was sufficient for finding the correct records. 我的数据库中有用用户输入搜索的记录,最初,这足以找到正确的记录。

"SELECT id FROM plants WHERE Flower LIKE '%" . $sanitizedUserInput . "%'"

This was working all well and good, but then things started to happen like, searching 'red' was getting plants with the characters 'red' in sequence in their Flower field, and not simply the whole word 'red'. 这一切都很好,但事情开始发生了,搜索“红色”是在Flower中按顺序获得字符“红色”的植物,而不仅仅是整个单词“红色”。

I was suggested to simply put a space either side of the user's input, but I know this will fail where the word is the first word in the field, or the last. 我被建议只是在用户输入的任一侧放置一个空格,但我知道这将是字段是字段中的第一个字或最后一个字时会失败。 I thought to myself, I should use a regular expression! 我心想,我应该用正则表达式! To search the word where it has a word boundary either side. 搜索任何一侧有单词边界的单词。

Unfortunately, I've never used regexs in a database before. 不幸的是,我以前从未在数据库中使用正则表达式。 How do you construct a query to search a db with a regex? 如何构建查询以使用正则表达式搜索数据库? Hopefully, it's as easy as this: 希望它像这样简单:

"SELECT id FROM plants WHERE Flower REGEX `/\b" . $sanitizedUserInput . " \b/`"

Yes, it's pretty much that easy. 是的,它非常简单。

MySQL Reference Manual - Regular Expressions MySQL参考手册 - 正则表达式

The word boundary sequences in MySQL regular expressions are [[:<:]] and [[:>:]] so you're going to end up with something like: MySQL正则表达式中的单词边界序列是[[:<:]][[:>:]]所以你最终会得到类似的东西:

$query = "SELECT id ".
            "FROM plants ".
            "WHERE Flower REGEXP '[[:<:]]".$sanitizedUserInput."[[:>:]]'";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM