$re = '/(?:if|for|while|foreach|catch|switch|try ?)\(((?>[^\(\)]+)|(?R))*\)/m';
$str = 'if(true)
if(true)
if(true)
echo \'\';
if (true)
echo \'true\';
elseif (false)
echo \'false\';
else
echo \'neither?\';
for(true)
echo \'\';
foreach (true) {
echo \'\';
}
if (true || true && (false || true)
|| true)
echo \'\';
while (true)
{
echo \'\';
}
if (true)
{
echo \'\';
}
for(true)
{
echo \'\';
}
try
{
echo \'\';
}
if (true || true && (false || true)
|| true) {
echo \'\';
}
for(true)
{
echo \'\';
}
if (true) {
echo \'\';
}
for(true)
{
echo \'\';
}
foreach(true)
{
echo \'\';
}
while(true)
{
echo \'\';
}
catch(true)
{
echo \'\';
}
switch(true)
{
echo \'\';
}
try {
echo \'\';
}';
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