Named backreferences with preg_replace

前端 未结 4 1088
说谎
说谎 2021-01-04 11:30

Pretty straightforward; I can\'t seem to find anything definitive regarding PHP\'s preg_replace() supporting named backreferences:

// should mat         


        
4条回答
  •  -上瘾入骨i
    2021-01-04 11:44

    you can use this :

    class oreg_replace_helper {
        const REGEXP = '~
    (?\d++)
        )
        |
        (?:
            \$\+?{(?P\w++)}
        )
        |
        (?:
            \x5Cg\<(?P\w++)\>
        )
    )?
    ~xs';
    
        protected $replace;
        protected $matches;
    
        public function __construct($replace) {
            $this->replace = $replace;
        }
    
        public function replace($matches) {
            var_dump($matches);
            $this->matches = $matches;
            return preg_replace_callback(self::REGEXP, array($this, 'map'), $this->replace);
        }
    
        public function map($matches) {
            foreach (array('num', 'name1', 'name2') as $name) {
                if (isset($this->matches[$matches[$name]])) {
                    return stripslashes($matches[1]) . $this->matches[$matches[$name]];
                }
            }
            return stripslashes($matches[1]);
        }
    }
    
    function oreg_replace($pattern, $replace, $subject) {
        return preg_replace_callback($pattern, array(new oreg_replace_helper($replace), 'replace'), $subject);
    }
    

    then you can use either \g ${name} or $+{name} as reference in your replace statement.

    cf (http://www.rexegg.com/regex-disambiguation.html#namedcapture)

提交回复
热议问题