我更換行的寫功能:
function replace($row){
$replaced = preg_replace_callback("~(\<span class=\"itemopener\"\>)(\d{1,5})\s(top\</span\>.*\<span class=\"allopener\"\>).{3}(\</span\>)~iU", function($matches){
$str = $matches[1] . $matches[3] . $matches[2] . $matches[4];
return $str;
}, $row);
return $replaced;
}
$s = '<span class="itemopener">82 top</span> <span class="allopener">all</span>';
$replaced = replace($s);
echo "<pre>" . print_r($replaced, 1) . "</pre>";
exit();
Working demo of the function
如果你將文件一行,並做一些簡單的檢查是否有這些跨度你想要替換,那麼你可以將它們發送到這個功能.. 但是與你指定的文件數量,這將需要一些時間。
對於路徑的所有文件的掃描,你可以使用我的回答有:scandir 稍加修改後,您可以修改它以只讀.htm文件,並返回到你,你的願望是什麼結構..
然後你採取所有掃描的htm文件,並用這樣的處理它們:
$allScannedFiles = array("......");
foreach($allScannedFiles as $key => $path){
$file = file_get_contents($path);
$lines = explode(PHP_EOL, $file);
$modifiedFile = "";
foreach($lines as $line){
if(strpos($line, "span") && strpos($line, "itemopener")){
$line = replace($line);
}
$modifiedFile .= $line . PHP_EOL;
}
file_put_contents($path, $modifiedFile);
}
我寫了這一個片段從頭部,因此需要一些測試.. 然後運行它,去讓自己咖啡和等待: ) 如果超時,您可以增加php超時。那怎麼辦被要求&回答這裏:how to increase timeout in php
或者你可以嘗試加載文件爲DOM文檔,並在該類documentation of DomDocument 但是,如果在某個地方的文件是無效的HTML,它可能會導致你的問題做替代品..
讓我們看看我是否rstand:你想要一個腳本讀取8000個HTML文件,然後在每個文件中搜索一行並將其替換爲其他行,對吧? –
1個目錄。 8000 htm文件。每個文件都有一大片文字,其中大約30個目標片段需要更改。所以大約有8000 * 30的替代品。 – Adrian33
這裏是一個示例頁面:http://hackerbra.in/unlisted/best_1360386661.htm – Adrian33