1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Yiisoft\Strings; |
6
|
|
|
|
7
|
|
|
final class CombinedRegexp |
8
|
|
|
{ |
9
|
|
|
private string $freeQuoter; |
10
|
|
|
private string $quoteReplacer; |
11
|
|
|
private string $compiledPattern; |
12
|
|
|
|
13
|
3 |
|
public function __construct( |
14
|
|
|
private array $patterns, |
15
|
|
|
private string $regexpQuoter = '/' |
16
|
|
|
) { |
17
|
3 |
|
$this->freeQuoter = $this->regexpQuoter === '/' ? '~' : '/'; |
18
|
3 |
|
$this->quoteReplacer = preg_quote($this->regexpQuoter, $this->regexpQuoter); |
19
|
3 |
|
$this->compiledPattern = $this->compilePatterns($this->patterns); |
20
|
|
|
} |
21
|
|
|
|
22
|
3 |
|
public function getCompiledPattern(): string |
23
|
|
|
{ |
24
|
3 |
|
return $this->compiledPattern; |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
public function matchAny(string $string, string $flags = 'i'): bool |
28
|
|
|
{ |
29
|
|
|
$pattern = $this->compiledPattern . $flags; |
30
|
|
|
|
31
|
|
|
return preg_match($pattern, $string) === 1; |
32
|
|
|
} |
33
|
|
|
|
34
|
3 |
|
public function matchPattern(string $string) |
35
|
|
|
{ |
36
|
3 |
|
return $this->patterns[$this->matchPatternPosition($string)]; |
37
|
|
|
} |
38
|
|
|
|
39
|
3 |
|
public function matchPatternPosition(string $string): int |
40
|
|
|
{ |
41
|
3 |
|
$match = preg_match($this->compiledPattern, $string, $matches); |
42
|
3 |
|
if ($match !== 1) { |
43
|
|
|
throw new \Exception( |
44
|
|
|
sprintf( |
45
|
|
|
'Failed to match pattern "%s" with string "%s".', |
46
|
|
|
$this->compiledPattern, |
47
|
|
|
$string, |
48
|
|
|
) |
49
|
|
|
); |
50
|
|
|
} |
51
|
|
|
|
52
|
3 |
|
return count($matches) - 1; |
53
|
|
|
} |
54
|
|
|
|
55
|
3 |
|
private function compilePatterns(array $patterns): string |
56
|
|
|
{ |
57
|
3 |
|
$quotedPatterns = []; |
58
|
3 |
|
for ($i = 0; $i < count($patterns); $i++) { |
|
|
|
|
59
|
3 |
|
$quotedPatterns[] = preg_replace( |
60
|
3 |
|
$this->freeQuoter . $this->regexpQuoter . $this->freeQuoter, |
61
|
3 |
|
$this->quoteReplacer, |
62
|
3 |
|
$patterns[$i] |
63
|
3 |
|
) . str_repeat('()', $i); |
64
|
|
|
} |
65
|
3 |
|
$combinedRegexps = '(?|' . implode('|', $quotedPatterns) . ')'; |
66
|
|
|
|
67
|
3 |
|
return $this->freeQuoter . $combinedRegexps . $this->freeQuoter; |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|
If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration: