<?php
$trim = function($str) {
return preg_replace('~\(+(\(((?:[^()]*|(?1))*)\))\)+|(\((?:[^()]*|\g{-1})*\))~', '$2$3', $str);
};
echo $trim('((((A))))'), "\n";
echo $trim('(((((B+C)*A)*(F))))'), "\n";
echo $trim('(A+B)(B+C)'), "\n";
echo $trim('(((((B+C)*A))))'), "\n";
echo str_repeat('-',15), PHP_EOL;
echo $trim('((A+B)+C)'), "\n";
echo $trim('(((A+B))+C)'), "\n";
echo $trim('((((A+B)+C))'), "\n";
echo $trim('(A+(B+C))'), "\n";
echo $trim('(A+((B+C)))'), "\n";
preferences:
59.27 ms | 402 KiB | 5 Q