1

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?

3
  • I guess: discover DBMS Commented Aug 27, 2013 at 9:40
  • 1
    If the problem concern DBMS I wouldn't even ask for that. But the project I'm working on contains data in a file. Commented Aug 27, 2013 at 9:51
  • tell the project manager or the teacher that (s)he is a noob and must give you the right tools for the job. An extreme solution would be: 1. parse the file into a DB (check SQLite if you're in a low resource setting) 2. elaborate using the new database 3. design a DB export routine with the desired format 4. ????? 5. PROFIT! Commented Aug 27, 2013 at 10:20

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

2

The basic process is:

open main file in readonly mode open secondary (temp) file in writeonly mode Loop: readline from main file process the line save to secondary file until end of file close both files delete the main file rename the secondary file. 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.