Created
May 1, 2023 15:53
-
-
Save sytnic/c468714b2aa0a592c86b97c9a6dfe180 to your computer and use it in GitHub Desktop.
Класс проверяет парность скобок
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Valid { | |
public $str; | |
public $check; | |
function __construct($str) { | |
$this->check = $this->valid_bracket($str); | |
} | |
/** | |
* We check all brackets in their pairs. | |
* | |
* @param string | |
* @return bool | |
*/ | |
private function valid_bracket($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) break; // обязательно, защита от }{ | |
} | |
if ($counter != 0) { | |
return false; | |
} | |
return true; | |
} | |
} | |
// Любая строка с любыми скобками | |
//$string = "{r}edfg}r}r{dfg{r{r}Ann{{r}r{r}}"; | |
//$string = "{{lajkdhf{adfa}{}adfasdfadf{}}}"; | |
$string = "{}{}west{{lajk[dhf{ad]fa}}}south()"; | |
// Покажем строку на экране | |
echo $string."<br><br>"; | |
// Инициализация класса | |
$valid = new Valid($string); | |
// Посмотрим на булево в переменной объекта | |
var_dump($valid->check); | |
echo "<br>"; | |
// Ответ на экране | |
if ($valid->check) { | |
echo "Все скобки корректны."; | |
} else { | |
echo "Некорректные пары скобок!"; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment