I was wandering if someone good in PHP could advise on how to validate brackets in an expression sting like this:
( 5 * 3 [ 6 ) - 6]
which is wrong expression. I need a function to to do this. Here is what I have tried so far:
<?php
function hasMatchedParenthesis($string) {
$counter1 = 0;
$counter2 = 0;
$length = strlen($string);
for ($i = 0;$i < $length; $i++) {
$char = $string[$i];
if( $char == '(' ) {
$counter1 ++;
} elseif( $char == ')' ) {
$counter1 --;
}
for($j =0;$j < $length; $j++) {
$char = $string[$j];
if( $char == '[' ) {
$counter2 ++;
} elseif( $char == ']' ) {
$counter2 --;
}
}
if( $counter1 < 0 || $counter2 < 0) {
return false;
}
}
echo 'ok';;
}
hasMatchedParenthesis('[5] * 3 - ( 4 - 7 * [3-6])'); // this is ok!
hasMatchedParenthesis('( 5 * 3 [ 6 ) - 6]'); // this returns as TRUE, but it is not!
?>
Pleas help me to resolve validation of '[ 6 )' thing! I dont know how to do it:(