亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

文件獲取內容和字符串替換多個文件

文件獲取內容和字符串替換多個文件

PHP
慕蓋茨4494581 2022-12-23 14:31:50
我在名為 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 并處理它們。有什么辦法可以做到這一點,或者我必須單獨獲取文件并單獨處理它們?謝謝。
查看完整描述

2 回答

?
慕的地8271018

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 上,您也可以嘗試使用replacereplexec或某些東西,因為它們接受多個文件。



查看完整回答
反對 回復 2022-12-23
?
婷婷同學_

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



查看完整回答
反對 回復 2022-12-23
  • 2 回答
  • 0 關注
  • 96 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號