[英]PHP - Edit/Delete particular line in a file
I have a file users.txt
which contains: 我有一个文件
users.txt
,其中包含:
"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. 我不会检查Expire日期是否大于当前日期时间,如果是,我想在该行的开头添加分号或直接删除该行。
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? 有什么建议么?
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. 如果要编辑该行,请使用
preg_match
并将已编辑的行推入新数组。
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. 最后,将
new array
保存到文件。
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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.