PHP. 替换字符串中的命名组

7
如何在替换字符串中使用命名分组? 该表达式创建了一个命名分组:
$re= "/(?P<name>[0-9]+)/";

我想替换这个表达式,但是它没有起作用。
preg_replace($re, "\{name}", $text);

PHP.net似乎preg_replace()不支持命名子模式,即'(?P<name>\w+)',这在许多情况下都是一个福音...虽然我想知道是否可能。 - Fabrício Matté
2个回答

3
您不能使用带有preg_replace()的非数字匹配名称。

也许有这个表达式的类似写法吗?s/(?P<name>[0-9]+)/$+{name}/; // Perl - ReinRaus

1
你可以使用这个:
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);
}

然后在替换语句中,您可以使用 \g ${name} 或 $+{name} 作为引用。

参考链接 (http://www.rexegg.com/regex-disambiguation.html#namedcapture)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接