文件获取内容并替换多个文件的字符串

问题描述 投票:0回答:2

我在名为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并进行处理。

有没有办法做到这一点,或者我只需要单独获取文件并分别处理它们?谢谢。

php foreach file-get-contents str-replace strpos
2个回答
0
投票

如果有其预定义的文件,则您不需要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)));

0
投票

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

在Linux上,您也可以尝试使用execreplacerepl进行某些操作,因为它们可以接受多个文件。

© www.soinside.com 2019 - 2024. All rights reserved.