Store the number of opening brackets at each index
for ( $ i = 1 ; $ i < $ len ; $ i ++ ) { if ( $ str [ $ i ] == ' ( ' ) $ open [ $ i + 1 ] = $ open [ $ i ] + 1 ; else $ open [ $ i + 1 ] = $ open [ $ i ] ; }