2010-10-20 48 views
6

好吧,最好的解決方案在PHP中搜索某些字符串的一堆文件內容,並用其他名稱替換它。在多個文件中查找和替換

完全像記事本++如何做,但顯然我不需要接口。

回答

22
foreach (glob("path/to/files/*.txt") as $filename) 
{ 
    $file = file_get_contents($filename); 
    file_put_contents($filename, preg_replace("/regexhere/","replacement",$file)); 
} 
2

所以我最近碰到了,我們的虛擬主機的PHP 5.2轉換爲5.3,並在這個過程中它打破了我們的Magento的安裝問題。我做了一些個人建議的調整,但發現還有一些破碎的區域。我意識到大部分問題都與Magento中存在的「toString」函數和現在不贊成使用的PHP分割函數有關。看到這一點,我決定嘗試創建一些代碼來查找和替換所有不同功能的實例。我成功地創造了這個功能,但不幸的是,這種射擊方式並不奏效。之後我仍然有錯誤。也就是說,我覺得代碼有很大的潛力,我想發佈我想出來的東西。

雖然請謹慎使用。我建議您壓縮文件的副本,以便您可以從備份中恢復,如果您有任何問題。

另外,您不一定要按原樣使用它。我提供的代碼作爲例子。您可能會想要更改被替換的內容。

代碼的工作方式是它可以找到並替換它放入的文件夾和子文件夾中的內容。我調整了它,以便它只會查找擴展名爲PHP的文件,但您可以根據需要更改它。在搜索時,它會列出它更改的文件。要使用此代碼,請將其保存爲「ChangePHPText.php」並將該文件上傳到需要進行更改的任何位置。然後您可以通過加載與該名稱關聯的頁面來運行它。例如,mywebsite.com \ ChangePHPText.php。

<?php 
    ## Function toString to invoke and split to explode 

    function FixPHPText($dir = "./"){ 
     $d = new RecursiveDirectoryIterator($dir); 
     foreach(new RecursiveIteratorIterator($d, 1) as $path){ 
      if(is_file($path) && substr($path, -3)=='php' && substr($path, -17) != 'ChangePHPText.php'){ 
       $orig_file = file_get_contents($path); 
       $new_file = str_replace("toString(", "invoke(",$orig_file); 
       $new_file = str_replace(" split(", " preg_split(",$new_file); 
       $new_file = str_replace("(split(", "(preg_split(",$new_file); 
       if($orig_file != $new_file){ 
       file_put_contents($path, $new_file); 
       echo "$path updated<br/>"; 
       } 
      } 
     } 
    } 

    echo "----------------------- PHP Text Fix START -------------------------<br/>"; 
    $start = (float) array_sum(explode(' ',microtime())); 
    echo "<br/>*************** Updating PHP Files ***************<br/>"; 
    echo "Changing all PHP containing toString to invoke and split to explode<br/>"; 
    FixPHPText("."); 

    $end = (float) array_sum(explode(' ',microtime())); 
    echo "<br/>------------------- PHP Text Fix COMPLETED in:". sprintf("%.4f", ($end-$start))." seconds ------------------<br/>"; 
    ?>