我在徘徊,如果有人擅长 PHP 可以建议如何验证表达式字符串中的括号,如下所示:
( 5 * 3 [ 6 ) - 6]
这是错误的表达。我需要一个函数来做到这一点。这是我到目前为止所尝试的:
<?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!
?>
请帮我解决“[6]”的验证问题!我不知道该怎么做:(