1

我正在尝试使用正则表达式从标签中提取信息,然后根据标签的各个部分返回结果。

preg_replace('/<(example )?(example2)+ />/', analyze(array($0, $1, $2)), $src);

所以我正在抓取零件并将其传递给analyze()函数。到达那里后,我想根据零件本身进行工作:

function analyze($matches) {
    if ($matches[0] == '<example example2 />')
          return 'something_awesome';
    else if ($matches[1] == 'example')
          return 'ftw';
}

等等。但是一旦我进入分析函数,$matches[0]就等于字符串' $0'。相反,我需要$matches[0]从 preg_replace() 调用中引用反向引用。我怎样才能做到这一点?

谢谢。

编辑:我刚刚看到了 preg_replace_callback() 函数。也许这就是我正在寻找的...

4

2 回答 2

8

你不能这样用preg_replace。你可能想要preg_replace_callback

于 2009-07-30T05:56:14.340 回答
0
$regex = '/<(example )?(example2)+ \/>/';
preg_match($regex, $subject, $matches);

// now you have the matches in $matches and you can process them as you want

// here you can replace all matches with modifications you made
preg_replace($regex, $matches, $subject);
于 2009-07-30T05:55:57.273 回答