$string = "this (is (a) test) with (two parenthesis) duh";
For a string like this you can use preg_match_all and use implode.
$string = "this (is (a) test) with (two parenthesis) duh";
$regex = '#\((([^()]+|(?R))*)\)#';
if (preg_match_all($regex, $string ,$matches)) {
echo implode(' ', $matches[1]);
} else {
//no parenthesis
echo $string;
}
Or you can use preg_replace, but with multiple parenthesis you'll lose the whitespace between them.
$regex = '#[^()]*\((([^()]+|(?R))*)\)[^()]*#';
$replacement = '\1';
echo preg_replace($regex, $replacement, $string);
I got a lot of help from this page, Finer points of PHP regular expressions.