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);
You can't - only numeric match names are usable with preg_replace()
.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With