title: Match parentheses with preg_match()
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/562606/regex-for-checking-if-a-string-has-mismatched-parentheses">Regex for checking if a string has mismatched parentheses?</a>  </p>
  </blockquote>
  
  
  
  <p>I'm trying to write a regex to match a string of numbers only, optionally enclosed in parentheses (regex must also check if parentheses are closed correctly, that is, if they exist in pars).
  So all of this should be considered valid by the regex:
  1234567
  123(45)6
  (123)(456)</p>
  
  <p>I came up with this using conditional patterns (note that I use spaces so the x modifier is required to make it ignore spaces):</p>
  
  <pre><code>$val = "(123)";
  $regex = "^( (\()? [0-9]+ (?(2)\)) )+$";
  $ret = preg_match("/{$regex}/x", $val, $matches);
  </code></pre>
  
  <p>However although it matches the above "(123)" correctly, it also matches the below which it shouldnt:
  "(123)45)" (second number has closing parentheses only)</p>
  
  <p>Anyone can help?</p>
  
  <p>NOTE: No nested parentheses allowed</p>