2013-03-14 41 views
0

如何獲得與例如preg_match_all()相匹配的所有匹配,並用空字符串替換結果?用正則表達式替換並提取匹配

我已經試過這樣的東西:

<?php 
$comments = array();    

$selectors = preg_replace_callback('~\*(?>(?:(?>([^*]+))|\*(?!\/))*)\*~', 
function ($match) { 
    $comments[] = $match[0]; 
    return ''; 
}, $input); 
?> 

但由於$評論變量似乎並沒有從匿名函數accessable不很好地工作。 我想我可以做的全局變量,但我真的不想搞砸了這樣的

+0

爲什麼不使用的preg_replace? – VladL 2013-03-14 10:46:59

+0

因爲然後我無法獲取/提取所有匹配(即被替換)。或者是可能的? – MichaelBS 2013-03-14 10:49:58

+0

嘗試函數聲明中的'use':http://www.php.net/manual/en/functions.anonymous.php – user1950929 2013-03-14 10:54:46

回答

0

的命名空間這應該工作:

<?php 
$comments = array();    

$selectors = preg_replace_callback('~\*(?>(?:(?>([^*]+))|\*(?!\/))*)\*~', 
function ($match) use (&$comments) { //add the variable $comments to the function scope 
    $comments[] = $match[0]; 
    return ''; 
}, $input); 
?>