Skip to content

Commit

Permalink
Add a limit to replace via regexp (#946)
Browse files Browse the repository at this point in the history
When using [Replace with Regexp](https://robo.li/tasks/File/#replace) there is no possibility to add a limit to the replaced items. This would be useful for instance when I replace version numbers in the DocBlock of fields and we want to replace only a single occurence.

for #123
  • Loading branch information
davidsneighbour authored May 22, 2020
1 parent 5d5e6d7 commit 30e78de
Showing 1 changed file with 19 additions and 1 deletion.
20 changes: 19 additions & 1 deletion src/Task/File/Replace.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,11 @@ class Replace extends BaseTask
*/
protected $from;

/**
* @var integer
*/
protected $limit = -1;

/**
* @var string|string[]
*/
Expand Down Expand Up @@ -112,6 +117,19 @@ public function regex($regex)
return $this;
}

/**
* If used with $this->regexp() how many counts will be replaced
*
* @param int $limit
*
* @return $this
*/
public function limit($limit)
{
$this->limit = $limit;
return $this;
}

/**
* {@inheritdoc}
*/
Expand All @@ -124,7 +142,7 @@ public function run()

$text = file_get_contents($this->filename);
if ($this->regex) {
$text = preg_replace($this->regex, $this->to, $text, -1, $count);
$text = preg_replace($this->regex, $this->to, $text, $this->limit, $count);
} else {
$text = str_replace($this->from, $this->to, $text, $count);
}
Expand Down

0 comments on commit 30e78de

Please sign in to comment.