简体   繁体   中英

How can I use RLIKE to effectively combine LIKE and IN, *and* escape regex characters where needed?

I need to figure out how to query my database for Serial A or Serial B or Serial C , however there are a variety of constraints making this difficult to navigate.

The previous solution used LIKE (eg SELECT * FROM Table WHERE Serial LIKE ) - this worked well for searching for all serials ( % ) or a specific serial ( Serial A ). However, I quickly found that IN and LIKE cannot be combined in MySql, and that the wildcards used by LIKE are not flexible enough to find Serial A or Serial B or Serial C .

(Note: The actual serials have a great deal of variation and no consistent convention - I'm aware that serials as simple as these basic examples could be found using the % wildcard)

My immediate thought was to use RLIKE instead - however some of the serials are named things such as B + 3 , and cannot be found without escaping. Here, I thought to use a method to escape the characters, such as preg_quote() - however therein lies more problems with the structure of the system...


Select Constraints Module

A combobox is populated by querying the database (eg SELECT DISTINCT Serial FROM Table ) from which the users can select a serial, and then submit the form. The selected serial is passed as a GET value to the next page.

View Results Module

The contents of a $serial variable are passed as a parameter to a SQL query to generate results on the page. $serial is either populated by the page the View Results Module is part of, or by the GET value passed to the page (if the value hasn't been populated by the page before the module is include d and there is no GET value, an error will be thrown).


Its this structure that's confusing me a little. It seems like it would be pretty straightforward to use RLIKE and preg_quote() to search for a serial if this was passed by the user. preg_quote() can be used on $serial before it is passed as a parameter and the updated ( WHERE Serial RLIKE ) query should work as expected. However, I still can't figure out how to search for more than one serial.

If I specify $serial as (Serial A | Serial B | Serial C) then preg_quote() will escape the regex characters and not find them. But if I don't use preg_quote() , serials such as B + 3 will not be found because regex characters are left unescaped.


I'd very much appreciate any feedback on improving this question - I've tried to explain it as clearly as possible but the complexity of the context and constraints make it difficult. Thank you.

转义子字符串,而不是最终的正则表达式。

"(" . preg_quote(serialA) . "|" . preg_quote(serialB) . "|" . preg_quote(serialC) . ")"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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