开发者

Regex end of string problem

开发者 https://www.devze.com 2023-02-12 23:06 出处:网络
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,

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

精彩评论

暂无评论...
验证码 换一张
取 消