Bu kodu vardır:
$count = 0;    
preg_replace('/test/', 'test'. $count, $content,-1,$count);
Her değiştirmek için, ben test0 edinin.
Ben test2 vb test0, test1, almak istiyorum.
 
				Kullan preg_replace_callback()  a>:
$count = 0;
preg_replace_callback('/test/', 'rep_count', $content);
function rep_count($matches) {
  global $count;
  return 'test' . $count++;
}
 
				Kullan preg_replace_callback()  a>:
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'
Not: global sert ve hızlı çözüm olduğunu, ancak bazı sorunları tanıtır, o yüzden tavsiye etmiyoruz kullanma.
 
				PHP5.3 serbest bırakılması ardından şimdi yukarıda Emil tarafından gündeme global soruna almak için bir kapatma ve use anahtar sözcüğünü kullanabilirsiniz:
    $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>";
Hangi döndürür:
item1,
item2,
Found match 1: 23623!,
foo1,
foo2,
foo3,
Found match 2: 923653245!,
bar1,
bar2,
Found match 3: 43572342!,
bar3,
bar4
Not use (&$count) işlev adını izleyen - bu bizi (ve bu başvuruya göre iletilir yapma ve fonksiyonu kapsamında bu nedenle yazılabilir fonksiyonu kapsamında $count okumanızı sağlar .)