我在名为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并进行处理。
有没有办法做到这一点,或者我只需要单独获取文件并分别处理它们?谢谢。
如果有其预定义的文件,则您不需要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)));
仅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";
}
}