2010-01-04 56 views
1

我試圖在我的數據文件中找到一些特定的塊並替換它們中的某些內容。之後,整個事情(與替換的數據)到一個新的文件。我此刻的代碼如下所示:preg_match_all內preg_replace問題

$content = file_get_contents('file.ext', true); 

//find certain pattern blocks first 
preg_match_all('/regexp/su', $content, $matches); 

foreach ($matches[0] as $match) { 
    //replace data inside of those blocks 
    preg_replace('/regexp2/su', 'replacement', $match); 
} 

file_put_contents('new_file.ext', return_whole_thing?); 

現在的問題是,我不知道該怎麼return_whole_thing。基本上,file.ext和new_file.ext幾乎與被替換的數據相同。 任何建議return_whole_thing應該在什麼位置?

謝謝!

回答

0

這可能是最好的加強你的正則表達式來找到原始模式內的子模式。這樣你可以調用preg_replace()並完成它。

$new_file_contents = preg_replace('/regular(Exp)/', 'replacement', $content); 

這可以用做 「()」 的正則表達式中。快速谷歌搜索「正則表達式子模式」導致this

2

你甚至不需要preg_replace;因爲你已經得到了比賽,你可以使用正常的str_replace像這樣:

$content = file_get_contents('file.ext', true); 

//find certain pattern blocks first 
preg_match_all('/regexp/su', $content, $matches); 

foreach ($matches[0] as $match) { 
    //replace data inside of those blocks 
    $content = str_replace($match, 'replacement', $content) 
} 

file_put_contents('new_file.ext', $content); 
0

我不知道我理解你的問題。也許你可以張貼的例子:

  • file.ext,原始文件
  • 要使用正則表達式,你想用
  • new_file.ext,所需輸出更換比賽什麼

如果你只是想讀file.ext,更換一個正則表達式匹配,並將結果保存在new_file.ext,所有需要的是:

$content = file_get_contents('file.ext'); 
$content = preg_replace('/match/', 'replacement', $content); 
file_put_contents('new_file.ext', $content);