I want to match the last "order by" in the string (e.g. $matches[1] = doo.time) I can sort of see the problem is with the (.*)
part but not sure what to change it to as it needs to be any character, any ideas?
$sql = "SELECT foo FROM blah ORDER BY foo.date 开发者_运维百科ORDER BY doo.time";
if (preg_match('/ORDER BY\s(.*)$/i', $sql, $matches)) {
echo "<pre>";
print_r($matches); exit;
}
You can greedily match (without capturing) everything before it. This will force the rest of the pattern to only match the last ORDER BY. This worked for me.
$sql = "SELECT foo FROM blah ORDER BY foo.date ORDER BY doo.time";
if (preg_match('/(?:.*)ORDER BY\s(.*)$/i', $sql, $matches)) {
echo "<pre>";
print_r($matches); exit;
}
If you're only looking for the column name, try this:
if (preg_match('/.*ORDER BY\s(.*?)(?:ASC|DESC)?\s*(?:LIMIT.*)?$/i', $sql, $matches)) {
echo "<pre>";
print_r($matches); exit;
}
精彩评论