Skip to content
Advertisement

Verify all brackets are properly open/closed

I am trying to write a function that will return true if brackets are closed, for example {[()]} and false if brackets are open, for example ) ( . I have problem with writing logic behind it. I have some idea like modulo, but it won’t work and I dont know what direction to look in.

function test($result) 
{
    if( $result % 2 === 0 ) { 
        return true;
    } else {
      return false;
    }
}

Advertisement

Answer

Starting by deleting any chars doesn’t mach sets {}, [] or (), I created helped functions exist to check if any of these sets exist in the string and also function replace to remove them. loop until nothing can be replaced. Finally check if the remaining length of string after deleting all sets is equal to 0. which means all brackets and parenthesis are properly opened and closed. Otherwise return false.

function exist($c, $s){
    return strpos($s, $c) !== false;
}
function replace($c, $s){
    return str_replace($c, "", $s);
}

function open_closed($str){
    //remove unneeded chars
    $str = preg_replace('/[^{}()[]]+/', '', $str);
    while(true){
        if(exist('{}', $str))
            $str = replace('{}', $str);
        elseif(exist('[]', $str))
            $str = replace('[]', $str);
        elseif(exist('()', $str))
            $str = replace('()', $str);
        else
            break;//if any of sets doesn't found, Exit the loop.
    }
    return !strlen($str);//or use strlen($str)===0
}
$string1 = '[{()[He9.😁*]{}}]';
/*
[{()[]}]
[{()}]
[{}]
[]

*/
var_dump(open_closed($string1));//true

$string2 = 'abc[({})][({)]99';
/*
[({})][({)]
[()][({)]
[][({)]
[({)]

*/
var_dump(open_closed($string2));//false
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement