Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP. Named groups in the replacement string

Tags:

regex

php

How to use named groups in the replacement string?
This expression creates a named group :

$re= "/(?P<name>[0-9]+)/";

I would like to replace this expression, but it does not work.

preg_replace($re, "\{name}", $text);
like image 201
ReinRaus Avatar asked Oct 08 '22 02:10

ReinRaus


2 Answers

You can't - only numeric match names are usable with preg_replace().

like image 110
Narf Avatar answered Oct 16 '22 19:10

Narf


you can use this :

class oreg_replace_helper {
    const REGEXP = '~
(?<!\x5C)(\x5C\x5C)*+
(?:
    (?:
        \x5C(?P<num>\d++)
    )
    |
    (?:
        \$\+?{(?P<name1>\w++)}
    )
    |
    (?:
        \x5Cg\<(?P<name2>\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, $limit = -1, &$count = 0) {
    return preg_replace_callback($pattern, array(new oreg_replace_helper($replace), 'replace'), $subject, $limit, $count);
}

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

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

like image 1
Olivier Parmentier Avatar answered Oct 16 '22 19:10

Olivier Parmentier