The problem is detecting the end of an order by
clause in the general case. These are some examples:
select * from (select * from t order by x, y) sq
select * from t order by x limit 1
select * from t order by (select 1)
Here I am working on the assumption that the order by
clause you are interested in is at the end of the sql statement and includes everything through the end of that statement. Under that assumption:
Regex Demo
<?php
$sql = 'select id,(ROW_NUMBER() OVER (ORDER BY (SELECT 1))) AS SerialNo,name,address from customer order by name';
if (preg_match('/.*(\border\s+by\s+.*)/is', $sql, $matches, PREG_OFFSET_CAPTURE)) {
$orderBy = $matches[1][0];
$offset = $matches[1][1];
$newSql = substr($sql, 0, $offset);
echo "The order by clause was: '$orderBy'.\n";
echo "The new sql is: '$newSql'.\n";
}
Prints:
The order by clause was: 'order by name'.
The new sql is: 'select id,(ROW_NUMBER() OVER (ORDER BY (SELECT 1))) AS SerialNo,name,address from customer '.