【问题标题】:File get contents and string replace for multiple files文件获取多个文件的内容和字符串替换
【发布时间】:2023-03-16 00:49:01
【问题描述】:

我在名为 test 的文件夹中有许多文件,alpha.php、beta.php 和 gamma.php。我需要获取这三个文件的内容,并将其中的一个字符串替换为另一个字符串。 要替换文件夹中的所有内容,这很有效:

foreach (new DirectoryIterator('./test') as $folder) {
    if ($folder->getExtension() === 'php') {
        $file = file_get_contents($folder->getPathname());
        if(strpos($file, "Hello You") !== false){
            echo "Already Replaced";
        }
        else {
            $str=str_replace("Go Away", "Hello You",$file);
            file_put_contents($folder->getPathname(), $str); 
            echo "done";
        }
    }
}

但我不想处理文件夹中的所有文件。我只想获取 3 个文件:alpha.php、beta.php 和 gamma.php 并处理它们。

有没有办法可以做到这一点,或者我必须单独获取文件并单独处理它们?谢谢。

【问题讨论】:

  • 你放弃了吗???
  • 一点也不。下面由 Lawrence Cherone 和 AbraCadaver 提供的答案奏效了。
  • 那么你应该接受其中之一。投票按钮下方的复选标记。
  • 哦,好的。两者都工作得很好,所以我不知道接受哪一个而不是另一个,我什至尝试接受两者,但似乎我们只允许接受一个,这就是为什么我只赞成他们。没问题,谢谢指导,我马上接受。

标签: php foreach file-get-contents str-replace strpos


【解决方案1】:

只要foreach你想要什么:

foreach (['alpha.php', 'beta.php', 'gamma.php'] as $filename) {
    $file = file_get_contents("./test/$filename");

    if(strpos($file, "Hello You") !== false){
        echo "Already Replaced";
    }
    else {
        $str = str_replace("Go Away", "Hello You", $file);
        file_put_contents("./test/$filename", $str); 
        echo "done";
    }
}

你不需要if,除非你真的需要echos 来查看何时有替换:

foreach (['alpha.php', 'beta.php', 'gamma.php'] as $filename) {
    $file = file_get_contents("./test/$filename");
    $str = str_replace("Go Away", "Hello You", $file);
    file_put_contents("./test/$filename", $str); 
}

或者你可以得到替换的数量:

    $str = str_replace("Go Away", "Hello You", $file, $count);
    if($count) {        
        file_put_contents("./test/$filename", $str); 
    }

在 Linux 上,您还可以尝试 exec 或带有 replacerepl 的东西,因为它们接受多个文件。

【讨论】:

    【解决方案2】:

    如果是预定义文件,则不需要 DirectoryIterator,只需将内容替换为 3 行或循环即可

    <?php
    $files = ['alpha.php', 'beta.php', 'gamma.php'];
    
    foreach ($files as $file) 
        file_put_contents('./test/'.$file, str_replace("Go Away", "Hello You", file_get_contents('./test/'.$file)));
    

    【讨论】:

      猜你喜欢
      • 2011-05-06
      • 2016-04-26
      • 1970-01-01
      • 1970-01-01
      • 2019-01-07
      • 2021-10-21
      • 1970-01-01
      • 2015-11-07
      相关资源
      最近更新 更多