2016-12-05 8 views
0

私はむしろPHPを初めて使い、文字列変数 'user'のインスタンスがあるすべての行を削除しようとしていました。現在のコードファイル内のすべての行を読み込んで特定の文字列を削除する

if($action == "removeUser") 
{ 
foreach(file('users.txt') as $line) 
{ 
    if (strpos($line, $parameters) !== false) 
    { 
     $line = ""; 
    } 
} 
} 

何らかの理由で、これはまったく効果がないようです。私は間違って何をしていますか?

答えて

0

ファイルを開いて行を読み取る必要があります。

<?php 

if($action == "removeUser") 
{ 
    $filename = "users.txt"; 

    // Open your file 
    $handle = fopen($filename, "r"); 

    $new_content=''; 

    echo "Valid input: <br><br>"; 
    // Loop through all the lines 
    while($line = fgets($handle)) 
    { 

     //try to find the string 'user' - Case-insensitive 
     if(stristr($line,"user")===FALSE) 
     { 
     // To remove white spaces 
     $line=trim($line); 

     if($line!='') echo $line."<br>"; 

     //if doesn't contain the string "user", 
     // add it to new input   
     $new_content.=$line."\n"; 
     } 
    } 

    // closes the file 
    fclose($handle); 

    $new_content=trim($new_content); // Remove the \n from the last line 

    echo "<br>Updating file with new content..."; 
    file_put_contents($filename,$new_content); 
    echo "Ok"; 
} 

?> 
+0

私はPHPには新しく、これは多くの助けとなりました – Reloaded

+0

空白を削除する方法はありますか? – Reloaded

+0

はい、 $ line = trim($ line);を使用して空白と空白行を削除できます。 –

関連する問題