|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Spatie\Regex; |
|
4
|
|
|
|
|
5
|
|
|
class ReplaceResult extends RegexResult |
|
6
|
|
|
{ |
|
7
|
|
|
/** @var string|array */ |
|
8
|
|
|
protected $pattern; |
|
9
|
|
|
|
|
10
|
|
|
/** @var string|array */ |
|
11
|
|
|
protected $replacement; |
|
12
|
|
|
|
|
13
|
|
|
/** @var string|array */ |
|
14
|
|
|
protected $subject; |
|
15
|
|
|
|
|
16
|
|
|
/** @var string|array */ |
|
17
|
|
|
protected $result; |
|
18
|
|
|
|
|
19
|
|
|
/** @var int */ |
|
20
|
|
|
protected $count; |
|
21
|
|
|
|
|
22
|
|
|
public function __construct($pattern, $replacement, $subject, $result, int $count) |
|
23
|
|
|
{ |
|
24
|
|
|
$this->pattern = $pattern; |
|
25
|
|
|
$this->replacement = $replacement; |
|
26
|
|
|
$this->subject = $subject; |
|
27
|
|
|
$this->result = $result; |
|
28
|
|
|
$this->count = $count; |
|
29
|
|
|
} |
|
30
|
|
|
|
|
31
|
|
|
public static function for($pattern, $replacement, $subject, $limit) |
|
|
|
|
|
|
32
|
|
|
{ |
|
33
|
|
|
$count = 0; |
|
34
|
|
|
|
|
35
|
|
|
try { |
|
36
|
|
|
if (is_callable($replacement)) { |
|
|
|
|
|
|
37
|
|
|
$replacement = function (array $matches) use ($pattern, $subject, $replacement) { |
|
38
|
|
|
return $replacement(new MatchResult($pattern, $subject, true, $matches)); |
|
39
|
|
|
}; |
|
40
|
|
|
|
|
41
|
|
|
$result = preg_replace_callback($pattern, $replacement, $subject, $limit, $count); |
|
|
|
|
|
|
42
|
|
|
} else { |
|
43
|
|
|
$result = preg_replace($pattern, $replacement, $subject, $limit, $count); |
|
|
|
|
|
|
44
|
|
|
} |
|
45
|
|
|
} catch (Exception $exception) { |
|
|
|
|
|
|
46
|
|
|
throw RegexFailed::replace($pattern, $subject, $exception->getMessage()); |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
|
|
if ($result === null) { |
|
|
|
|
|
|
50
|
|
|
throw RegexFailed::replace($pattern, $subject, static::lastPregError()); |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
|
|
return new static($pattern, $replacement, $subject, $result, $count); |
|
|
|
|
|
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
public function result() |
|
57
|
|
|
{ |
|
58
|
|
|
return $this->result; |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
|
|
public function count() |
|
62
|
|
|
{ |
|
63
|
|
|
return $this->count; |
|
64
|
|
|
} |
|
65
|
|
|
} |
|
66
|
|
|
|