$re = '/(?:\$\w+(?:\((?<arg>(?R)|(?:\"[^\"]*\")|(?:[^\$\"\&\s\(\)][^\s\(\)]*))(?:(?:\+| )(?&arg))*\))?)|(?<var>\&\w+)/m';
$str = '$test($test(test &var1 $var2) $test(jean) jean) # should full-match
$test($test(test $var1 $var2) $test(foo) bar) # should not full-match
$test("&test") # should not full-match
$test("foo&test") # should not full-match
$test("&test" &test) # should full-match
&test # should full-match
$test(" &test") # should not full-match
$test # should not full-match
&test(foo) # should not full-match
&test(&foo $bar()) # should not full-match
$test((&test)) # should not full-match
$foo(bar(&baz)) # should not full match
$test(&test &test) # should not full match
$test( &test) # should not full match
$test(&test ) # should not full match';
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