2009-10-08 31 views
1

這樣的事情,但我並不想這樣做2次:如何在PHP中匹配並替換一個滿口?

preg_match_all($pattern,$string,$matches); 
$string = preg_replace($pattern,'',$string); 
+0

什麼是你的精確模式?乾草堆? – powtac 2009-10-08 11:36:42

+0

你能更具體一點,並且實際描述你正在嘗試做什麼? – James 2009-10-08 11:52:54

+0

在你的代碼中,第一行似乎是多餘的。除非你以後使用火柴。但是,如果你想以後用火柴,也想更換琴絃,那麼你需要兩個正則表達式 – andho 2009-10-08 12:21:44

回答

-1

你的意思是這樣的嗎?

$string = preg_replace(preg_match_all($pattern,$string,$matches),'',$string); 

更新:

我是這麼認爲的,你想是這樣的..但現在你可以看到,它不可能沒有事情複雜(如@gnud答案)。所以答案是否定的,你不能在一行中完成。

+3

將不起作用,preg_match_all返回一個int不匹配。 – James 2009-10-08 11:37:54

+0

不工作,但似乎他得到了我的意思。 – Misier 2009-10-08 11:44:06

+0

所以可能你現在得到了答案,它不可能在一行中完成。 :) – TigerTiger 2009-10-08 12:35:11

1

好吧,

所以你想捕獲匹配,並在一次函數調用中替換。我猜你不想處理一個昂貴的正則表達式兩次,否則我看不出有什麼理由讓你的代碼不易讀。

反正

你可以嘗試使用preg_replace_callback()。喜歡的東西:

class MatchReplace { 

    var $matches; 
    var $pattern; 
    var $replacement; 
    var $string; 
    var $matchCount; 

    function __construct($pattern, $replacement) { 
     $this->replacement = $replacement; 
     $this->pattern = $pattern; 
    } 

    function matchAndReplace($string) { 
     $this->string = $string; 

     var_dump($string); 
     var_dump($this->pattern); 

     return preg_replace_callback($this->pattern, 
       array($this, '_worker'), $string, -1, $this->matchCount); 
    } 


    function _worker($matches) { 
     echo "Matches:\n"; 
     var_dump($matches); 
    } 
} 

實例運行:

echo "<pre>\n"; 
$m = new MatchReplace('|(abc)|', ''); 
echo "\nResult: \n".$m->matchAndReplace('XXXabcYYY'); 

echo "\n</pre>"; 

輸出:

string(9) "XXXabcYYY" 
string(7) "|(abc)|" 
Matches: 
array(2) { 
    [0]=> 
    string(3) "abc" 
    [1]=> 
    string(3) "abc" 
} 

Result: 
XXXYYY 
+0

這是太複雜了,我甚至會喜歡它的兩倍.. – Misier 2009-10-08 12:04:50

+0

除非你的正則表達式是瘋狂的複雜,​​沒有充分的理由這樣做。只需運行兩次:首先匹配,然後替換。 – gnud 2009-10-08 12:10:55

+0

這樣的正則表達式最好運行兩次 – andho 2009-10-08 12:19:16

0

如果你不需要花哨更換的規則(比如正則表達式),你應該使用str_replace函數( )函數而不是ereg_replace()或preg_replace()。

http://uk.php.net/str_replace

這將盡一切的發生,只有1個命令。

0

通過它你正在做2個完全獨立的東西的樣子。

preg_match_all($pattern,$string,$matches); // return all the matches 
$string = preg_replace($pattern,'',$string); // replace all the matches in the string 

所以你實際上並沒有做任何事情兩次。除非你使用$匹配,否則第一行是無關緊要的,如果你打算繼續使用preg_replace後綴。

0
preg_match_all($pattern1,$string,$matches); 
$result = preg_grep($pattern2, $matches);