fire
fire

Reputation: 21531

Regex end of string problem

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;
}

Upvotes: 0

Views: 885

Answers (2)

Sander Marechal
Sander Marechal

Reputation: 23216

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;
}

Upvotes: 3

BoltClock
BoltClock

Reputation: 723518

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;
}

Upvotes: 2

Related Questions