2009-07-30 102 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);