如何在替换字符串中使用命名组?
此表达式创建一个命名组:
$re= "/(?P<name>[0-9]+)/";
我想替换这个表达式,但它不起作用。
preg_replace($re, "\{name}", $text);
您不能 - 只有数字匹配名称可用于preg_replace()
.
你可以使用这个:
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} 作为参考。
cf(http://www.rexegg.com/regex-disambiguation.html#namedcapture)