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
|
15 |
|
public function __construct( |
14
|
|
|
/** |
15
|
|
|
* @var string[] |
16
|
|
|
*/ |
17
|
|
|
private array $patterns, |
18
|
|
|
private string $regexpQuoter = '/' |
19
|
|
|
) { |
20
|
15 |
|
$this->freeQuoter = $this->regexpQuoter === '/' ? '~' : '/'; |
21
|
15 |
|
$this->quoteReplacer = preg_quote($this->regexpQuoter, $this->regexpQuoter); |
22
|
15 |
|
$this->compiledPattern = $this->compilePatterns($this->patterns); |
23
|
|
|
} |
24
|
|
|
|
25
|
15 |
|
public function getCompiledPattern(): string |
26
|
|
|
{ |
27
|
15 |
|
return $this->compiledPattern; |
28
|
|
|
} |
29
|
|
|
|
30
|
9 |
|
public function matchAny(string $string, string $flags = 'i'): bool |
31
|
|
|
{ |
32
|
9 |
|
$pattern = $this->compiledPattern . $flags; |
33
|
|
|
|
34
|
9 |
|
return preg_match($pattern, $string) === 1; |
35
|
|
|
} |
36
|
|
|
|
37
|
3 |
|
public function matchPattern(string $string): string |
38
|
|
|
{ |
39
|
3 |
|
return $this->patterns[$this->matchPatternPosition($string)]; |
40
|
|
|
} |
41
|
|
|
|
42
|
6 |
|
public function matchPatternPosition(string $string): int |
43
|
|
|
{ |
44
|
6 |
|
$match = preg_match($this->compiledPattern, $string, $matches); |
45
|
6 |
|
if ($match !== 1) { |
46
|
|
|
throw new \Exception( |
47
|
|
|
sprintf( |
48
|
|
|
'Failed to match pattern "%s" with string "%s".', |
49
|
|
|
$this->compiledPattern, |
50
|
|
|
$string, |
51
|
|
|
) |
52
|
|
|
); |
53
|
|
|
} |
54
|
|
|
|
55
|
6 |
|
return count($matches) - 1; |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
/** |
59
|
|
|
* @param string[] $patterns |
60
|
|
|
* @return string |
61
|
|
|
*/ |
62
|
15 |
|
private function compilePatterns(array $patterns): string |
63
|
|
|
{ |
64
|
15 |
|
$quotedPatterns = []; |
65
|
15 |
|
for ($i = 0; $i < count($patterns); $i++) { |
|
|
|
|
66
|
15 |
|
$quotedPatterns[] = preg_replace( |
67
|
15 |
|
$this->freeQuoter . $this->regexpQuoter . $this->freeQuoter, |
68
|
15 |
|
$this->quoteReplacer, |
69
|
15 |
|
$patterns[$i], |
70
|
15 |
|
) . str_repeat('()', $i); |
71
|
|
|
} |
72
|
15 |
|
$combinedRegexps = '(?|' . implode('|', $quotedPatterns) . ')'; |
73
|
|
|
|
74
|
15 |
|
return $this->freeQuoter . $combinedRegexps . $this->freeQuoter; |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|
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: