我有一个php方法,它应该删除"命令的所有出现。来自mysql查询字符串的mysql语句。
示例1:
STRING:SELECT * FROM table ORDER BY name
结果:SELECT * FROM table
示例2:
STRING:SELECT a.* FROM (SELECT * FROM table ORDER BY name, creation_date) AS a ORDER BY a.name
结果:SELECT a.* FROM (SELECT * FROM table) AS a
我现在的问题是:如何实现这个目标。
我尝试了以下内容:
if (stripos($sql, 'ORDER BY') !== false) {
$sql = preg_replace('/\sORDER\ BY.+/i', '', $sql);
}
但这适用于示例1,但不适用于示例2
答案 0 :(得分:3)
您可以使用的正则表达式为ORDER BY.*?(?=\s*LIMIT|\)|$)
。
示例代码:
$re = "/ORDER BY.*?(?=\\s*LIMIT|\\)|$)/mi";
$str = "SELECT * FROM table ORDER BY name\n\nSELECT a.* FROM (SELECT * FROM table ORDER BY name, created_at) AS a ORDER BY a.name\n\nSELECT t0.* FROM table t0 WHERE t0.created_at IS NOT NULL ORDER BY t0.name, t0.created_at, t0.status LIMIT 10 OFFSET 10";
$result = preg_replace($re, "", $str);
答案 1 :(得分:1)
ORDER BY.*?(?=\)|$)
试试这个。empty space
。见。演示。
https://regex101.com/r/tJ2mW5/22
$re = "/ORDER BY.*?(?=\\)|$)/mi";
$str = "SELECT * FROM table ORDER BY name\nSELECT a.* FROM (SELECT * FROM table ORDER BY name, creation_date) AS a ORDER BY a.name";
$subst = "";
$result = preg_replace($re, $subst, $str);