开发者

Regex to parse a MySQL query for JOIN's

开发者 https://www.devze.com 2023-02-12 02:54 出处:网络
I am using regex to parse a MySQL query for JOIN\'s, currently using this: if (preg_match_all(\'/\\s(LEFT|INNER|OUTER|RIGHT)?\\sJOIN\\s(.*)/i\', $sql, $matches)) {

I am using regex to parse a MySQL query for JOIN's, currently using this:

if (preg_match_all('/\s(LEFT|INNER|OUTER|RIGHT)?\sJOIN\s(.*)/i', $sql, $matches)) {
    print_r($matches); exit;
}

This doesn't quite work as I want an array of strings like this:

[0] => formats ON articles.article_format_id = formats.format_id
[1] => article_categories ON articles.article_id = article_categories.article_id

My current regex returns this:

Array
(
    [0] => Array
        (
            [0] =>  INNER JOIN formats ON articles.article_format_id = formats.format_id INNER JOIN article_categories ON articles.article_id = article_categories.article_id 
        )

    [1] => Array
        (
            [0] => INNER
        )

    [2] => Array
        (
            [0] => formats ON articles.article_format_id = formats.format_id INNER JOIN article_categories ON articl开发者_高级运维es.article_id = article_categories.article_id 
        )

)

Any ideas?


The greedy .* might take everything to the end. So change the regex to:

/(?:LEFT|INNER|OUTER|RIGHT)?\sJOIN\s((?:(?!(?:LEFT|INNER|OUTER|RIGHT)?\sJOIN).)+)/i

See here: rubular

And you might have to use preg_match_all to find all matches.

0

精彩评论

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