1
|
|
|
<?php |
2
|
|
|
namespace PHPHtmlParser\Selector; |
3
|
|
|
|
4
|
|
|
/** |
5
|
|
|
* This is the parser for the selctor. |
6
|
|
|
* |
7
|
|
|
* |
8
|
|
|
*/ |
9
|
|
|
class Parser implements ParserInterface |
10
|
|
|
{ |
11
|
|
|
|
12
|
|
|
/** |
13
|
|
|
* Pattern of CSS selectors, modified from 'mootools' |
14
|
|
|
* |
15
|
|
|
* @var string |
16
|
|
|
*/ |
17
|
|
|
protected $pattern = "/([\w\-:\*>]*)(?:\#([\w\-]+)|\.([\w\-]+))?(?:\[@?(!?[\w\-:]+)(?:([!*^$]?=)[\"']?(.*?)[\"']?)?\])?([\/, ]+)/is"; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* Parses the selector string |
21
|
|
|
* |
22
|
|
|
* @param string $selector |
23
|
|
|
*/ |
24
|
255 |
|
public function parseSelectorString(string $selector): array |
25
|
|
|
{ |
26
|
255 |
|
$selectors = []; |
27
|
|
|
|
28
|
255 |
|
$matches = []; |
29
|
255 |
|
preg_match_all($this->pattern, trim($selector).' ', $matches, PREG_SET_ORDER); |
30
|
|
|
|
31
|
|
|
// skip tbody |
32
|
255 |
|
$result = []; |
33
|
255 |
|
foreach ($matches as $match) { |
34
|
|
|
// default values |
35
|
255 |
|
$tag = strtolower(trim($match[1])); |
36
|
255 |
|
$operator = '='; |
37
|
255 |
|
$key = null; |
38
|
255 |
|
$value = null; |
39
|
255 |
|
$noKey = false; |
40
|
255 |
|
$alterNext = false; |
41
|
|
|
|
42
|
|
|
// check for elements that alter the behavior of the next element |
43
|
255 |
|
if ($tag == '>') { |
44
|
3 |
|
$alterNext = true; |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
// check for id selector |
48
|
255 |
|
if ( ! empty($match[2])) { |
49
|
18 |
|
$key = 'id'; |
50
|
18 |
|
$value = $match[2]; |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
// check for class selector |
54
|
255 |
|
if ( ! empty($match[3])) { |
55
|
48 |
|
$key = 'class'; |
56
|
48 |
|
$value = $match[3]; |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
// and final attribute selector |
60
|
255 |
|
if ( ! empty($match[4])) { |
61
|
207 |
|
$key = strtolower($match[4]); |
62
|
|
|
} |
63
|
255 |
|
if ( ! empty($match[5])) { |
64
|
198 |
|
$operator = $match[5]; |
65
|
|
|
} |
66
|
255 |
|
if ( ! empty($match[6])) { |
67
|
198 |
|
$value = $match[6]; |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
// check for elements that do not have a specified attribute |
71
|
255 |
|
if (isset($key[0]) && $key[0] == '!') { |
72
|
3 |
|
$key = substr($key, 1); |
73
|
3 |
|
$noKey = true; |
74
|
|
|
} |
75
|
|
|
|
76
|
255 |
|
$result[] = [ |
77
|
255 |
|
'tag' => $tag, |
78
|
255 |
|
'key' => $key, |
79
|
255 |
|
'value' => $value, |
80
|
255 |
|
'operator' => $operator, |
81
|
255 |
|
'noKey' => $noKey, |
82
|
255 |
|
'alterNext' => $alterNext, |
83
|
|
|
]; |
84
|
255 |
|
if (trim($match[7]) == ',') { |
85
|
3 |
|
$selectors[] = $result; |
86
|
171 |
|
$result = []; |
87
|
|
|
} |
88
|
|
|
} |
89
|
|
|
|
90
|
|
|
// save last results |
91
|
255 |
|
if (count($result) > 0) { |
92
|
255 |
|
$selectors[] = $result; |
93
|
|
|
} |
94
|
|
|
|
95
|
255 |
|
return $selectors; |
96
|
|
|
} |
97
|
|
|
} |
98
|
|
|
|