1

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 articles.article_id = article_categories.article_id 
        )

)

Any ideas?

3
  • What about: UPDATE foo SET bar='join me in my regex quest!'? :) Commented Feb 21, 2011 at 11:07
  • true, how can I improve the regex? Commented Feb 21, 2011 at 11:08
  • @Bart Kiers: Missing white spaces: UPDATE foo SET bar=' join me! ' Commented Feb 21, 2011 at 11:09

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks, almost works! take a look at pastebin.com/pfdNTzvS if you run that code the last element in the $matches array [2] is what I am looking for however it leaves 'INNER' on the end of the first string! can this be improved upon at all?
Ok, I change it, so it does omit the INNER and other prefixes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.