2 回答

TA貢獻1796條經驗 獲得超4個贊
正是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";
}
}
你不需要 theif除非你真的需要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 上,您也可以嘗試使用replace或replexec
或某些東西,因為它們接受多個文件。

TA貢獻1844條經驗 獲得超8個贊
如果它是預定義的文件,那么您不需要 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)));
- 2 回答
- 0 關注
- 96 瀏覽
添加回答
舉報