How to replace text with a regex pattern and integrate a counter in the replacement text?

前端 未结 3 1488
孤街浪徒
孤街浪徒 2021-01-27 07:30
function parse($string){
    $counter = 0;
    
    $string = preg_replace("_\\[b\\](.*?)\\[/b\\]_si", \'\'. $counter .\'. $1&l         


        
3条回答
  •  野性不改
    2021-01-27 07:44

    I would solve it with a small class with the counter as property and the callback is a method of the class.

    class Increaser {
        private $counter;
    
        public function replace($string) {
            $this->counter = 0;
    
            return preg_replace_callback("_\[b\](.*?)\[/b\]_si", array($this, 'createReplacement'), $string);
        }
    
        private function createReplacement($matches) {
            ++$this->counter;
    
            return ''. $this->counter .'. ' . $matches[1] . '';
        }
    }
    

提交回复
热议问题