【发布时间】: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