2009-07-30 32 views
1

我试图使用正则表达式从标记中提取信息,然后根据标记的各个部分返回结果。用作另一个函数参数的PHP preg_replace()反向引用

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()函数。也许这就是我正在寻找的...

回答

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);