$re = '/^[^\)][0-9 \((AND|OR)]*$/m';
$str = '1ORAND2
2
1 OR 2 OR OR 15 15 15 AND 6
1 OR (9 AND OR3)
1 OR ( 2 AND 3) AND 2
( 2 2OR3) AND 1
(12AND13 AND1)OR(4 AND5)
((2AND3 AND 1)OR(4AND5))AND OR 6';
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