打印大多数子括号内的字符并打印该括号计数


Print the characters inside most child parenthesis and print that parenthesis count

我有一个字符串$string = "(a(b,c)((d,e))(f,g))";

我想打印大多数子括号内的字符,并打印括号计数

输出应为

> Most child parenthesis: 3
> Value contains: d,e

下面是我的快速实现:

$string = "(a(b,c)((d,e))(f,g))";
$count = 0;
$max_count = 0;
$final_string = '';
for ( $i=0; $i<strlen($string); $i++ )
{
    if ( $string[$i] == '(' )
    {
        $count++;
        if ( $count > $max_count )
        {
            $max_count = $count;
            $final_string = "";
        }
    }
    else if ( $string[$i] == ')' )
    {
        $count--;
    }
    else if ( $count == $max_count )
    {
        $final_string .= $string[$i];
    }
}
echo "Most child parenthesis: ", $max_count, "'nValue contains: ", $final_string;

你可以在这里看到它的作用。