Regex for checking if a string has mismatched parentheses?

后端 未结 8 2144
一生所求
一生所求 2020-11-29 05:41

In a PHP script, what regex should I use to check for mismatched parentheses in a string? Things that I want to allow include:

  • This is (ok)
  • This (is)
8条回答
  •  醉梦人生
    2020-11-29 05:57

    Working php without regex:

    function analyse($input){
        $len = strlen($input);
        $depth = 0;
        for ($i = 0; $i < $len; $i++) {
            $depth += $input[$i] == '(';
            $depth -= $input[$i] == ')';
            if ($depth < 0) break;
        }
        if ($depth != 0) return false;
            else return true;
    }
    $check_nestled = analyse('(5 * 2) + ((2 + 2) - 4)');
    if($check_nestled){
        // do stuff, everything is ok
    }
    

提交回复
热议问题