Search code examples
phpforeachfile-get-contentsstr-replacestrpos

File get contents and string replace for multiple files


I have a number of files, alpha.php, beta.php and gamma.php in a folder named test. I need to get the contents of these three files and and replace a string in them with another string. To replace everything in the folder, this worked:

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

But I don't want to process all the files in the folder. I just want to get the 3 files: alpha.php, beta.php and gamma.php and process them.

Is there a way I can do this or I have to just get the files individually and process them individually? Thanks.


Solution

  • Just foreach what you want:

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

    You don't need the if unless you really need the echos to see when there are replacements:

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

    Or you can get the count of replacements:

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

    On Linux you could also try exec or something with replace or repl as they accept multiple files.