你是非常接近:
$str = preg_replace('/abc/', '123', $str, 1); // will replace first 'abc'
$str = preg_replace('/abc/', '456', $str); // will replace all others
的原因,這會工作,是因爲第二個正則表達式的第一次出現,實際上是第二個項目。
臨:可讀性很強,非常容易理解和執行
精讀:字符串將regexed兩次(壞的大型字符串),選擇是有限的
如果這不是你願意的話,可以使用preg_replace_callback()
$firstHasBeenFound = false;
function magicFunction($matches){
global $firstHasBeenFound;
print_r($matches);
if(!$firstHasBeenFound){
/* do something for the first time */ ;
$firstHasBeenFound = true; // save for next round
}
else{
/* do something for the test */ ;
}
}
$str = preg_replace_callback('/abc/', 'magicFunction', $str);
臨:很多更多的變種可以進行,更多的控制Ø版本代碼,字符串的唯一一個解析
精讀:比較難讀/執行
在這個例子中,我使用$firstHasBeenFound
,但你可以使用一個增量做點什麼各2次,或東西時,你會發現比賽7,等
除了'preg_replace('/ abc /','123',$ str,1); preg_replace('/ abc /','456',$ str,1);'...'preg_replace_callback()'帶有一個回調,該回調保持每個替換的靜態計數並且可以根據該計數修改其響應 –