Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
493 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use preg_replace_callback():

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...