问题
I have a php method, which should remove all occurences of an "order by" mysql statement from a mysql query string.
Example 1:
STRING: SELECT * FROM table ORDER BY name
RESULT: SELECT * FROM table
Example 2:
STRING: SELECT a.* FROM (SELECT * FROM table ORDER BY name, creation_date) AS a ORDER BY a.name
Result: SELECT a.* FROM (SELECT * FROM table) AS a
My question now is: How to achive this.
I have tried the following:
if (stripos($sql, 'ORDER BY') !== false) {
$sql = preg_replace('/\sORDER\ BY.+/i', '', $sql);
}
But this would work for example 1, but not for example 2
回答1:
Regex you can use is ORDER BY.*?(?=\s*LIMIT|\)|$)
.
Sample code:
$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);
Demo
回答2:
ORDER BY.*?(?=\)|$)
Try this.Replace by empty space
.See demo.
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);
来源:https://stackoverflow.com/questions/29231433/php-regex-remove-order-by-from-query-string