I am trying to figure out, how to remove surrounding brackets in math expressions using php.
Some cases are: 
(A+B)(B+C) should stay the same
((((A)))) should get A
((A(B+C))) should get A*(B+C)
(((((B+C)*A)))) should get (B+C)*A
I cannot find a solution which is right in any case. Using math rules like distributive property is no option.
I am not looking for copy-and-paste algorithm, just a criterion which fits all of my cases. This is the latest attempt, I tried different methods like regex, but I did not figure it out.
function removeSurroundingBrackets($str)
{
$res=$str;
if(strcmp($res[0],'(')===0 && strcmp($res[strlen($res)-1],')')===0)
{
    $firstOther=0;
    for(; $firstOther<strlen($str);$firstOther++)
    {
        if(strcmp($str[$firstOther],'(')!==0)
            break;
    }
    $removableCount=0;
    $removableCount=substr_count($str,')',$firstOther)-substr_count($str,'(',$firstOther);
}
return substr($str,$removableCount,-$removableCount);
}
EDIT: I found a Solution:
function removeSurroundingBrackets($str)
{
    $res=$str;
    while(strcmp($res[0],'(')===0 && strcmp($res[strlen($res)-1],')')===0)
    {
        if($this->checkBrackets(substr($res,1,-1)))
            $res=substr($res,1,-1);
        else
            return $res;
    }
    return $res;
}
function checkBrackets($str)
{
    $currdepth=0;
    foreach(str_split($str) as $char)
    {
        if(strcmp($char,')')===0)
        {
            if($currdepth<=0)
                return false;
            else
                $currdepth--;
        }
        else if(strcmp($char,'(')===0)
            $currdepth++;
    }
    return true;
}
 
     
    