如何根据正则表达式选择行?

时间:2016-02-15 15:00:11

标签: php mysql regex

我有一张这样的表:

// mytable
+----+----------------------+
| id |       sentence       |
+----+----------------------+
| 1  | thIs! is, a** tEst?  |
| 2  | and also This ^ is&  |
| 3  | --it^% is tOo.       |
+----+----------------------+

我也有一个变量:

$str = "this-is-a-test";
/* the above string is made according to this:
   strtolower(trim(preg_replace('~[^0-9a-z]+~i', '-', $str)));
*/

这也是我的疑问:

SELECT * FROM mytable WHERE sentence = '$str';

现在我想要输出:

+----+----------------------+
| id |       sentence       |
+----+----------------------+
| 1  | thIs! is, a** tEst?  |
+----+----------------------+

如何在搜索之前暂时将该正则表达式应用于列?

1 个答案:

答案 0 :(得分:0)

您可以在MySQL中使用正则表达式执行搜索:) 不要混淆! RegEx将由SGBD执行,而不是由PHP执行!!

SELECT * FROM mytable WHERE sentence REGEXP '$str';

了解更多信息,请访问MySQL文档MySQL REGEXP