views:

233

answers:

3

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..

+1  A: 

preg_replace_callback() will allow you to operate upon the match before returning it for subsequent replacement.

Ignacio Vazquez-Abrams
+1  A: 

Use preg_replace_callback():

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

function rep_count($matches) {
  global $count;
  return 'test' . $count++;
}
cletus
+2  A: 

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.

Emil Ivanov
Global has no more problems than the overcomplicated object solution. People get stuck on globals in PHP because of the C/C++/etc stigmatism, which is misplaced. Globals in PHP are simply request-scoped variables. Less hand-wringing, more pragmatism.
cletus