Skip to content

Commit bb1580f

Browse files
committed
Improve code: Don't count closing tags
1 parent ffcae7d commit bb1580f

File tree

1 file changed

+12
-22
lines changed

1 file changed

+12
-22
lines changed

app/Parsers/SimpleHtmlParser.php

+12-22
Original file line numberDiff line numberDiff line change
@@ -2,37 +2,27 @@
22

33
class SimpleHtmlParser implements HtmlParserInterface
44
{
5+
private $tagCounts = [];
56
public function parse(string $html): array
67
{
7-
$tagCounts = [];
8-
$pos = 0;
98

10-
while (($start = strpos($html, '<', $pos)) !== false) {
11-
$end = strpos($html, '>', $start);
12-
if ($end === false) {
13-
break;
14-
}
9+
$this->tagCounts = [];
1510

16-
$tag = substr($html, $start + 1, $end - $start - 1);
17-
$tag = strtolower($tag);
11+
$pattern = '/<([a-zA-Z0-9]+)(?:\s|>)/';
1812

19-
if (strpos($tag, '/') === 0) {
20-
// Закрывающий тег, удалить его из подсчета
21-
$tag = substr($tag, 1);
22-
} elseif (strpos($tag, ' ') !== false) {
23-
// Пометить и удалить атрибуты
24-
$tag = substr($tag, 0, strpos($tag, ' '));
25-
}
13+
preg_match_all($pattern, $html, $matches);
2614

27-
if (isset($tagCounts[$tag])) {
28-
$tagCounts[$tag]++;
15+
$tags = $matches[1];
16+
17+
foreach ($tags as $tag) {
18+
$tag = strtolower($tag);
19+
if (isset($this->tagCounts[$tag])) {
20+
$this->tagCounts[$tag]++;
2921
} else {
30-
$tagCounts[$tag] = 1;
22+
$this->tagCounts[$tag] = 1;
3123
}
32-
33-
$pos = $end + 1;
3424
}
3525

36-
return $tagCounts;
26+
return $this->tagCounts;
3727
}
3828
}

0 commit comments

Comments
 (0)