Home > php教程 > php手册 > body text

PHP如何判断表达式的括号是否匹配(附代码)

PHPz
Release: 2018-10-17 15:46:28
Original
2320 people have browsed it

下面小编就为大家带来一篇PHP判断表达式中括号是否匹配的简单实例。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧

如下所示:

<?php  
/** 
 * title: 判断表达式中括号是否匹配 
 * Description: () 匹配 )(不匹配 利用压栈和出栈 
 * @author Mr Lv   

 */   
function isValid($expstr) { 
  $temp = array(); 
  for ($i=0; $i<strlen($expstr); $i++) { 
    $ch = $expstr[$i]; 
    switch($ch) { 
      case &#39;(&#39;: 
        array_push($temp, &#39;(&#39;); 
        break; 
      case &#39;)&#39;: 
        if (empty($temp) || array_pop($temp) != &#39;(&#39;) { 
          return "缺少左括号("; 
        } 
    } 
  } 
  return empty($temp) == true ? "表达式匹配" : "缺少右括号)"; 
} 
$expstrA = "(1+3(6*4)-(2+3))()("; 
$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); 
?>
Copy after login

页面信息:

缺少右括号) 
表达式匹配 
缺少左括号(
Copy after login

 以上就是小编为大家带来的PHP判断表达式中括号是否匹配的简单实例全部内容了。

 

【相关教程推荐】

1. php编程从入门到精通全套视频教程
2. php从入门到精通 
3. bootstrap教程

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template