php实现判断表达式中括号等是否匹配

<?php  
/** 
 * title: 判断表达式中括号是否匹配 
 * Description: () 匹配 )(不匹配 利用压栈和出栈 
 * 使用数组来模拟进栈和出栈array_push() array_pop()
 * @author Liu   
 
 */ 
header("Content-Type: text/html;charset=utf-8"); 
function isValid($expstr) { 
  $temp = []; 
  for ($i=0; $i<strlen($expstr); $i++) { 
    $ch = $expstr[$i];    
    switch($ch) { 
      case '(': 
        array_push($temp, '('); 
        break; 
      case ')': 
        if (empty($temp) || array_pop($temp) != '(') { 
          return "缺少左括号("; 
        } 
        break; 
      case '[': 
        array_push($temp, '['); 
        break; 
      case ']': 
        if (empty($temp) || array_pop($temp) != '[') { 
          return "缺少左中括号["; 
        }
        break; 
      case '{': 
        array_push($temp, '{'); 
        break; 
      case '}': 
        if (empty($temp) || array_pop($temp) != '{') { 
          return "缺少左大括号{"; 
        }
        break; 
    } 
  }    
  return empty($temp) == true ? "表达式匹配" : "表达式不匹配"; 
} 
//举个例子
$expstrA = "{(6*4)[4*5-1(2*5)]}"; 
$expstrB = "(1+3(6*4)-(2+3))()"; 
$expstrC = "(1+3(6*4)-(2+3)))"; 
echo isValid($expstrA);//输出表达式匹配 
echo "<br>"; 
echo isValid($expstrB);//输入表达式匹配 
echo "<br>"; 
echo isValid($expstrC);//输入缺少左括号(


?>

猜你喜欢

转载自blog.csdn.net/star_xing123/article/details/84848132
今日推荐