$re = '/(["\'])\s*(SELECT)(?:\s+.*)?\s+(FROM)(?:\s+.*)?\1(?:[^\w]|$)/m';
$str = ' SELECT * FROM tbl -- no match - not in a string
"SELECT * FROM tbl" -- matches - in a double-quoted string
\'SELECT * FROM tbl;\' -- matches - in a single-quoted string
\'SELECT * FROM it\'s -- no match - letter after end quote
"SELECT * FROM tbl\' -- no match - quotation marks don\'t match
\'SELECT * FROM tbl" -- no match - quotation marks don\'t match
"select * from tbl" -- no match - keywords not upper case
\'Select * From tbl\' -- no match - still not all upper case
"SELECT col1 FROM" -- matches - even though no table name
\' SELECT col1 FROM \' -- matches - as above with more whitespace
\'SELECT col1, col2 FROM\' -- matches - with multiple columns';
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