Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to increment count in the replacement string when using preg_replace?

I have this code :

$count = 0;    
preg_replace('/test/', 'test'. $count, $content,-1,$count);

For every replace, I obtain test0.

I would like to get test0, test1, test2 etc..

like image 874
anno Avatar asked Feb 02 '10 14:02

anno


3 Answers

Use preg_replace_callback():

$count = 0;
preg_replace_callback('/test/', 'rep_count', $content);

function rep_count($matches) {
  global $count;
  return 'test' . $count++;
}
like image 110
cletus Avatar answered Nov 11 '22 05:11

cletus


Use preg_replace_callback():

class TestReplace {
    protected $_count = 0;

    public function replace($pattern, $text) {
        $this->_count = 0;
        return preg_replace_callback($pattern, array($this, '_callback'), $text);
    }

    public function _callback($matches) {
        return 'test' . $this->_count++;
    }
}

$replacer = new TestReplace();
$replacer->replace('/test/', 'test test test'); // 'test0 test1 test2'

Note: Using global is the hard-and-fast solution but it introduces some problems, so I don't recommend it.

like image 6
Emil Ivanov Avatar answered Nov 11 '22 05:11

Emil Ivanov


Following the release of PHP5.3 we can now use a closure and the use keyword to get around the global issue raised by Emil above:

    $text = "item1,\nitem2,\nFINDME:23623,\nfoo1,\nfoo2,\nfoo3,\nFINDME:923653245,\nbar1,\nbar2,\nFINDME:43572342,\nbar3,\nbar4";
$pattern = '/FINDME:(\d+)/';
$count = 1;
$text = preg_replace_callback(  $pattern
                            ,   function($match) use (&$count) {
                                    $str = "Found match $count: {$match[1]}!";
                                    $count++;
                                    return $str;
                                }
                            ,   $text
                            );
echo "<pre>$text</pre>";

Which returns:

item1,
item2,
Found match 1: 23623!,
foo1,
foo2,
foo3,
Found match 2: 923653245!,
bar1,
bar2,
Found match 3: 43572342!,
bar3,
bar4

Note the use (&$count) following the function name - this allows us to read $count in the scope of the function (the & making it passed by reference and therefore writeable from the scope of the function).

like image 4
Gruffy Avatar answered Nov 11 '22 06:11

Gruffy