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