2 回答
TA貢獻(xiàn)1796條經(jīng)驗(yàn) 獲得超4個(gè)贊
正是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 來(lái)查看何時(shí)有替換:
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);
}
或者您可以獲得替換次數(shù):
$str = str_replace("Go Away", "Hello You", $file, $count);
if($count) {
file_put_contents("./test/$filename", $str);
}
在 Linux 上,您也可以嘗試使用replace或replexec或某些東西,因?yàn)樗鼈兘邮芏鄠€(gè)文件。
TA貢獻(xiàn)1844條經(jīng)驗(yàn) 獲得超8個(gè)贊
如果它是預(yù)定義的文件,那么您不需要 DirectoryIterator,只需用 3 行或一個(gè)循環(huán)替換內(nèi)容
<?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 關(guān)注
- 121 瀏覽
添加回答
舉報(bào)
