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

anno picture anno · Feb 2, 2010 · Viewed 10.6k times · Source

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

Answer

cletus picture cletus · Feb 2, 2010

Use preg_replace_callback():

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

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