duanche8554 2013-08-27 09:39
浏览 23
已采纳

PHP - 编辑/删除文件中的特定行

I have a file users.txt which contains:

"ID" "Access" ;Expire>>26-08-2013<<
"ID" "Access" ;Expire>>27-08-2013<<
"ID" "Access" ;Expire>>28-08-2013<<

I wan't to check if the Expire date is greater than current datetime, and if so I want to add a semicolon at the begin of that line or simply delete that line.

The code i wrote so far for that is following:

$files = file('users.txt');
foreach ($files as $line) {

    $pattern = '/>>(.*)<</';
    preg_match($pattern, $line, $matches);
    $expiredate = strtotime($matches[1]);
    $currdate = strtotime(date('d-m-Y'));
    if ($currdate > $expiredate) {
        echo 'access expired... edit/delete the line<br/>';
    } else {
        echo 'do nothing, its ok -> switching to the next line...<br/>';
    }

 }

It retrieves the 'expire date' from every single line from file. It also checks if it's greater than current date but at this point i don't know how to edit (by adding semicolon at the begin) or delete the line which satisfy the condition.

Any suggestions?

  • 写回答

2条回答 默认 最新

  • duanmianzhou5353 2013-08-27 09:59
    关注

    Try like this one:

    $files = file('users.txt');
    
    $new_file = array();
    foreach ($files as $line) {
    
        $pattern = '/>>(.*)<</';
        preg_match($pattern, $line, $matches);
        $expiredate = strtotime($matches[1]);
        $currdate = strtotime(date('d-m-Y'));
        if ($currdate > $expiredate) {
            // For edit
            $line = preg_replace('/condition/', 'replace', $line); // Edit line with replace
            $new_file[] = $line; // Push edited line
    
            //If you delete the line, do not push array and do nothing
        } else {
            $new_file[] = $line; // push line new array
        }
     }
    
    file_put_contents('users.txt', $new_file);
    

    If you want to edit that line, use preg_match and push edited line to new array.

    If you want to delete that line, do nothing. Just ignore.

    If you want switching to the next line, push currently line to new array.

    At final save new array to file.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置