Home > Backend Development > PHP Tutorial > A simple example of PHP judging whether the brackets in the expression match

A simple example of PHP judging whether the brackets in the expression match

巴扎黑
Release: 2023-03-07 22:00:01
Original
1299 people have browsed it

The following editor will bring you a simple example of PHP judging whether the brackets in the expression match. The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor and take a look.

is as follows:


##

<?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

Page information:


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

The above is the detailed content of A simple example of PHP judging whether the brackets in the expression match. For more information, please follow other related articles on the PHP Chinese website!

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 Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template