2014-03-02 91 views
0
if(isset($_POST['submit'])){ 
$fn="file.php"; 
$str=file_get_contents($fn); 

if (empty($str)){ 
die('Failed to fetch data'); 
}else{ 
$oldMessage = "Hello"; 
$deletedFormat = "bye"; 
$str = str_replace($oldMessage, $deletedFormat,$str,$count); 

if(file_put_contents($fn, $str)){ 
    echo 'Total replace: '.$count; 
} 
} 

} 

我試圖刪除我打開的文件中的字符串。但是,它不起作用。刪除文件中的字符串php

+0

將'error_reporting(-1);'放在文件頂部。修復所有錯誤。另外,閱讀['file_get_contents()'](http://php.net/file_get_contents)的文檔(提示:你不應該使用'fopen()')。 –

+0

'file_get_contents'和'file_put_contents'是'fopen'和'fclose'的包裝。你不應該把它們結合起來。只需使用'file_get_contents'。 – kba

回答

4

file_get_contents預計第一個參數是文件名而不是文件資源。

http://php.net/file_get_contents

所以要fopenfclose的調用是沒有必要的,而不是把它像這樣

$str = file_get_contents($fn); 
0

不要忘記檢查函數結果。下面是一個簡單的示例腳本:

$fn="file.php"; 
$str=file_get_contents($fn); 

if (empty($str)){ 
    die('Failed to fetch data'); 
}else{ 
    $oldMessage = "Hello"; 
    $deletedFormat = ""; 
    $str = str_replace($oldMessage, $deletedFormat,$str,$count); 

    if(file_put_contents($fn, $str)){ 
     echo 'Total replace: '.$count; 
    } 
}