-
-
Notifications
You must be signed in to change notification settings - Fork 71
/
Copy pathfirst_match.php
51 lines (42 loc) · 1.33 KB
/
first_match.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
<?php
declare(strict_types=1);
namespace Psl\Regex;
use Psl\Type;
use function preg_match;
/**
* Determine if $subject matches the given $pattern and return the first matches.
*
* @template T of array|null
*
* @param non-empty-string $pattern The pattern to match against.
* @param ?Type\TypeInterface<T> $capture_groups What shape does the matching items have?
*
* @throws Exception\RuntimeException If an internal error accord.
* @throws Exception\InvalidPatternException If $pattern is invalid.
*
* @return (T is null ? array<array-key, string> : T)|null
*/
function first_match(
string $subject,
string $pattern,
?Type\TypeInterface $capture_groups = null,
int $offset = 0
): ?array {
$matching = Internal\call_preg(
'preg_match',
static function () use ($subject, $pattern, $offset): ?array {
$matching = [];
$matches = preg_match($pattern, $subject, $matching, 0, $offset);
return $matches === 0 ? null : $matching;
}
);
if ($matching === null) {
return null;
}
$capture_groups ??= Type\dict(Type\array_key(), Type\string());
try {
return $capture_groups->coerce($matching);
} catch (Type\Exception\CoercionException $e) {
throw new Exception\RuntimeException('Invalid capture groups', 0, $e);
}
}