2016-12-05 1 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);을 사용하여 제거 할 수 있습니다. –

관련 문제