Skip to content

Instantly share code, notes, and snippets.

@AlexMcowkin
Created August 7, 2018 11:46
Show Gist options
  • Save AlexMcowkin/1e36d001931c690a691896315ad233e1 to your computer and use it in GitHub Desktop.
Save AlexMcowkin/1e36d001931c690a691896315ad233e1 to your computer and use it in GitHub Desktop.
Проверка строки на верное количество скобок на php
<?php
$string = 'This is (ok)';
function bracketValidation($string)
{
$counter = 0;
$openBracket = ['(','{','['];
$closedBracket = [')','}',']'];
$length = strlen($string);
for($i = 0; $i<$length; $i++)
{
$char = $string[$i];
if(in_array($char, $openBracket))
{
$counter ++;
}
elseif(in_array($char, $closedBracket))
{
$counter --;
}
}
if($counter != 0)
{
return false;
}
return true;
}
?>
@sytnic
Copy link

sytnic commented May 1, 2023

...
for($i = 0; $i<$length; $i++)
{
    ...
    if ($counter < 0) break;
}
...

Иначе будет ошибка в случае:
}{
)(

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment