1

How to extract the string below using regex (preg_match or preg_replace):

SELECT id FROM table WHERE 1 would match " id "

SELECT name, (SELECT price FROM table2 WHERE id = '1') var FROM table1 WHERE 1 would match " name, (SELECT price FROM table2 WHERE id = '1') var "

3
  • I can easily do the first case but in the cases looking like the second one it gets " name, (SELECT price " instead of " name, (SELECT price FROM table2 WHERE id = '1') var " because of the FROM in the select clause Commented Dec 8, 2013 at 1:08
  • Regular expressions are not a suitable tool for this problem. Try code.google.com/p/php-sql-parser instead. Commented Dec 8, 2013 at 1:33
  • Also, duplicate of stackoverflow.com/questions/12034100/… Commented Dec 8, 2013 at 1:33

1 Answer 1

2

If your goal is to do some advanced things with your queries, the best way is to use a sql parser ("php sql parser" for example, as suggested). To only get the content between SELECT and FROM, you can use this:

$test_queries = array(
    'SELECT id FROM table WHERE 1',
    'SELECT name, (SELECT price, (SELECT 1+1) FROM table2) var FROM table1',
    'SELeCT FROMAGE, \'\\\'((\', \'"\")(\', "\'\"\\\" FrOM table');

$pattern = <<<'LOD'
~
 # definitions
 (?(DEFINE)
   # content inside quotes
   (?<quoted> (["']) (?> [^"'\\]++ | \\{2} | \\. | (?!\g{-1})["'] )*+ \g{-1} )

   # nested parenthesis
   (?<nested> ( \( (?> [^()"']++ | \g<quoted> | (?-1) )*+ \) ) )

   # content between SELECT and FROM
   (?<content> (?> [^(F"']++ | \BF | F(?!ROM\b) | \g<quoted> | \g<nested> )++ )
 )

 # pattern
 \bSELECT\b (?<result> \g<content> ) FROM\b
~xis
LOD;

foreach ($test_queries as $k => $test_query) {
    if (preg_match($pattern, $test_query, $match))
        echo '<br/>' . $k . ') ' . trim($match['result']);
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.