使用preg_replace时如何增加替换字符串中的计数?

ann*_*nno 10 php regex string preg-replace

我有这个代码:

$count = 0;    
preg_replace('/test/', 'test'. $count, $content,-1,$count);
Run Code Online (Sandbox Code Playgroud)

对于每次替换,我获得test0.

我想得到test0,test1,test2等.

cle*_*tus 15

用途preg_replace_callback():

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

function rep_count($matches) {
  global $count;
  return 'test' . $count++;
}
Run Code Online (Sandbox Code Playgroud)


Emi*_*nov 6

用途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'
Run Code Online (Sandbox Code Playgroud)

注意:使用global是一种快速的解决方案,但它引入了一些问题,所以我不推荐它.

  • Global 没有比过于复杂的对象解决方案更多的问题。人们因为 C/C++/etc 的污名而陷入 PHP 中的全局变量,这是错误的。PHP 中的全局变量只是请求范围的变量。少操心,多务实。 (2认同)