Php regex: remove order by from query string

老子叫甜甜 提交于 2021-02-19 08:06:12

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!