PHP判断表达式中括号是否匹配

  1. <?php   
  2.       
  3. function isValid($expstr) {  
  4.     $temp = array();  
  5.     for ($i=0; $i<strlen($expstr); $i++) {  
  6.         $ch = $expstr[$i];  
  7.         switch($ch) {  
  8.             case '(':  
  9.                 array_push($temp'(');  
  10.                 break;  
  11.             case ')':  
  12.                 if (emptyempty($temp) || array_pop($temp) != '(') {  
  13.                     return "缺少左括号(";  
  14.                 }  
  15.         }  
  16.     }  
  17.     return emptyempty($temp) == true ? "表达式匹配" : "缺少右括号)";  
  18. }  
  19. $expstrA = "(1+3(6*4)-(2+3))()(";  
  20. $expstrB = "(1+3(6*4)-(2+3))()";  
  21. $expstrC = "(1+3(6*4)-(2+3)))";  
  22. echo isValid($expstrA);  
  23. echo "<br>";  
  24. echo isValid($expstrB);  
  25. echo "<br>";  
  26. echo isValid($expstrC);  
  27. ?>  

结果:

  1. 缺少右括号)  
  2. 表达式匹配  
  3. 缺少左括号(  

猜你喜欢

转载自blog.csdn.net/only_xiaohang/article/details/80850644
今日推荐