dsds661730652211 2016-12-05 02:43
浏览 243
已采纳

读取文件中的所有行并删除包含某些字符串的行

I'm rather new to PHP, and was trying to remove all lines where any instance of the string variable 'user' appears. My current code

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

For some reason this doesn't seem to have any effect at all. What am I doing wrong?

  • 写回答

1条回答 默认 最新

  • duanqun9740 2016-12-05 03:19
    关注

    You need to open the file and read the lines.

    <?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."
    "; 
          }
        }
    
        // closes the file
        fclose($handle);
    
        $new_content=trim($new_content); // Remove the 
     from the last line
    
        echo "<br>Updating file with new content...";
        file_put_contents($filename,$new_content);
        echo "Ok";
    }
    
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?