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
$count = 0;
preg_replace_callback('/test/', 'rep_count', $content);
function rep_count($matches) {
global $count;
return 'test' . $count++;
}
Run Code Online (Sandbox Code Playgroud)
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
是一种快速的解决方案,但它引入了一些问题,所以我不推荐它.
归档时间: |
|
查看次数: |
9840 次 |
最近记录: |