搜索和替换目录中的文件

Search and Replace Files in Directory

<span class="itemopener">82 top</span>&nbsp;<span class="allopener">all</span>

如何将上面的内容更改为:

<span class="itemopener">top</span>&nbsp;<span class="allopener">82</span>

在 html 文件中使用 PHP,其中包含大约 30 个 HTML 片段。

注意:82 可以是任何大于 1 的整数。

此外,我想 运行 从我放置在目录中的新文件中获取此脚本,这将 运行 为 8000 个 HTML 中的每一个搜索和替换一次该目录中的文件(脚本在完成之前不能超时 - 也许是一些反馈。)

我编写了替换行的函数:

 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>&nbsp;<span class="allopener">all</span>';
$replaced = replace($s);

echo "<pre>" . print_r($replaced, 1) . "</pre>";
exit();

Working demo of the function

如果你想一行一行地获取文件,并做一些简单的检查是否有那些你想替换的跨度,那么你可以将它们发送到这个函数中.. 但是根据您指定的文件数量,需要一些时间。

要扫描路径中的所有文件,您可以使用我的回答: 稍作编辑后,您可以将其修改为只读 .htm 文件,并且 return 给您想要的结构..

然后你获取所有扫描的 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

或者您可以尝试将文件加载为 DOMDocument 并对其进行替换 class documentation of DomDocument 但如果文件中某处无效 html,可能会给您带来问题..

我正在使用@Jimmmy 创建的函数(将范围 d{2} 替换为 d{1,5} 因为 "Note: 82 can be any integer above 1")并添加了文件搜索(对其进行了测试并且效果很好):

<?php

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;
}

foreach ( glob( "*.html" ) as $file )         // GET ALL HTML FILES IN DIRECTORY.
{ $lines = file( $file );                     // GET WHOLE FILE AS ARRAY OF STRINGS.
  for ( $i = 0; $i < count( $lines ); $i++ )  // CHECK ALL LINES IN ARRAY.
    $lines[ $i ] = replace( $lines[ $i ] );   // REPLACE PATTERN IF FOUND.
  file_put_contents( $file,$lines );          // SAVE ALL ARRAY IN FILE.
}
?>