2016-04-03 93 views
-2

我試圖做一個非常簡單的搜索並替換php腳本,但它不起作用。你可以請教我,我在這裏做錯了什麼?在文件中找到並替換

if(isset($_GET['fnr'])) { 
    $find = $_GET['find']; 
    $replace = $_GET['replace']; 

    $path_to_file = 'index.php'; 
    $file_contents = file_get_contents($path_to_file); 
    $file_contents = str_replace("$find","$replace",$file_contents); 
    file_put_contents($path_to_file,$file_contents); 
} 
+1

什麼問題? _它不工作_是不夠的。 – Reversal

+0

不行不行。不知道爲什麼。 – Ganga

+0

...你有沒有試過調試你的代碼? '$ _GET ['find']'不是空的嗎?你對'index.php'有讀寫權限?在'str_replace'後修改'$ file_contents'? [如何創建一個最小化,完整和可驗證的示例](https://stackoverflow.com/help/mcve) – Reversal

回答

0

$file_contents = str_replace("$find","$replace",$file_contents);

textfile.php刪除"

我的名字Frayne,我的名字也konok

PHP

$find = "My name"; 
    $replace = "name"; 

    $path_to_file = 'textfile.php'; 
    $file_contents = file_get_contents($path_to_file); 
    $file_contents = str_replace($find,$replace, $file_contents); 
    file_put_contents($path_to_file,$file_contents); 

輸出:

我的名字Frayne,名字也konok

輸出字符串從文件中刪除My

+0

你可以說使用這樣一個構造'「$ string」'是沒用的,但這不成問題,'str_replace'接受'strings'作爲params和afaik'「$ string」'是一樣的字符串作爲'$ string' – Reversal

+0

正確的,我不得不說'在字符串中使用'是無用的',正如我做的例子,它完美的作品。 –