$re = '/SELECT (.*) (?:INTO (.*)).*\sFROM (.*)(?:\sWHERE (.*)).*(?:\sHAVING (.*)).*(?:\sORDER BY (.*)).*/m';
$str = 'SELECT test1.col1, test1.col2, test1.col3, "aaa" AS Error, x as y INTO test2
FROM test1, test3
WHERE (((test1.col2)="bbb") AND ((test1.col3) Is Null Or (test1.col3)="ccc"))
HAVING 1=1
ORDER BY 1;';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
// Print the entire match result
var_dump($matches);
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for PHP, please visit: http://php.net/manual/en/ref.pcre.php