我写了替换行的函数:
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);
}
我从头开始写了这个sn-p,所以需要进行一些测试..
然后运行它,去给自己煮咖啡并等待:)
如果它会超时,你可以增加 php 超时。如何做到这一点在此处询问和回答:how to increase timeout in php
或者,您可以尝试将文件加载为 DOMDocument 并对该类进行替换 documentation of DomDocument
但是如果文件中的某处不是有效的 html,它可能会给你带来问题..