這樣的事情,但我並不想這樣做2次:如何在PHP中匹配並替換一個滿口?
preg_match_all($pattern,$string,$matches);
$string = preg_replace($pattern,'',$string);
這樣的事情,但我並不想這樣做2次:如何在PHP中匹配並替換一個滿口?
preg_match_all($pattern,$string,$matches);
$string = preg_replace($pattern,'',$string);
你的意思是這樣的嗎?
$string = preg_replace(preg_match_all($pattern,$string,$matches),'',$string);
更新:
我是這麼認爲的,你想是這樣的..但現在你可以看到,它不可能沒有事情複雜(如@gnud答案)。所以答案是否定的,你不能在一行中完成。
將不起作用,preg_match_all返回一個int不匹配。 – James 2009-10-08 11:37:54
不工作,但似乎他得到了我的意思。 – Misier 2009-10-08 11:44:06
所以可能你現在得到了答案,它不可能在一行中完成。 :) – TigerTiger 2009-10-08 12:35:11
好吧,
所以你想捕獲匹配,並在一次函數調用中替換。我猜你不想處理一個昂貴的正則表達式兩次,否則我看不出有什麼理由讓你的代碼不易讀。
反正
你可以嘗試使用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
如果你不需要花哨更換的規則(比如正則表達式),你應該使用str_replace函數( )函數而不是ereg_replace()或preg_replace()。
這將盡一切的發生,只有1個命令。
通過它你正在做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後綴。
preg_match_all($pattern1,$string,$matches);
$result = preg_grep($pattern2, $matches);
什麼是你的精確模式?乾草堆? – powtac 2009-10-08 11:36:42
你能更具體一點,並且實際描述你正在嘗試做什麼? – James 2009-10-08 11:52:54
在你的代碼中,第一行似乎是多餘的。除非你以後使用火柴。但是,如果你想以後用火柴,也想更換琴絃,那麼你需要兩個正則表達式 – andho 2009-10-08 12:21:44