<?php
$re = '#^(([^()]|\((?1)\))*)$#';
foreach (array('', '1', '()', '(())', '1(2)3', '(()())', '()()', '()x()1') as $value) echo "'$value' (OK) -> " . (preg_match($re, $value) ?
'OK' : 'invalid') . "\n";
foreach (array('1(', ')', '(()', '12)3', '((())', '()(()') as $value) echo "'$value' (invalid) -> " . (preg_match($re, $value) ?
'OK' : 'invalid') . "\n";
PD9waHAKCiRyZSA9ICcjXigoW14oKV18XCgoPzEpXCkpKikkIyc7Cgpmb3JlYWNoIChhcnJheSgnJywgJzEnLCAnKCknLCAnKCgpKScsICcxKDIpMycsICcoKCkoKSknLCAnKCkoKScsICcoKXgoKTEnKSBhcyAkdmFsdWUpCgllY2hvICInJHZhbHVlJyAoT0spIC0+ICIgLiAocHJlZ19tYXRjaCgkcmUsICR2YWx1ZSkgPyAnT0snIDogJ2ludmFsaWQnKSAuICJcbiI7Cgpmb3JlYWNoIChhcnJheSgnMSgnLCAnKScsICcoKCknLCAnMTIpMycsICcoKCgpKScsICcoKSgoKScpIGFzICR2YWx1ZSkKCWVjaG8gIickdmFsdWUnIChpbnZhbGlkKSAtPiAiIC4gKHByZWdfbWF0Y2goJHJlLCAkdmFsdWUpID8gJ09LJyA6ICdpbnZhbGlkJykgLiAiXG4iOwo=