Store the number of closing brackets at each index
for ( $ i = $ len - 2 ; $ i >= 0 ; $ i -- ) { if ( $ str [ $ i ] == ' ) ' ) $ close [ $ i ] = $ close [ $ i + 1 ] + 1 ; else $ close [ $ i ] = $ close [ $ i + 1 ] ; }