PHP-编辑/删除文件中的特定行
我有一个文件users.txt,其中包含:PHP-编辑/删除文件中的特定行,php,file,edit,Php,File,Edit,我有一个文件users.txt,其中包含: "ID" "Access" ;Expire>>26-08-2013<< "ID" "Access" ;Expire>>27-08-2013<< "ID" "Access" ;Expire>>28-08-2013<< 我不想检查过期日期是否大于当前日期时间,如果是,我想在该行的开头添加分号,或者干脆删除该行 到目前为止,我为此编写的代码如下: $files = file('user
"ID" "Access" ;Expire>>26-08-2013<<
"ID" "Access" ;Expire>>27-08-2013<<
"ID" "Access" ;Expire>>28-08-2013<<
我不想检查过期日期是否大于当前日期时间,如果是,我想在该行的开头添加分号,或者干脆删除该行
到目前为止,我为此编写的代码如下:
$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/>';
}
}
它从文件的每一行检索“过期日期”。它还检查它是否大于当前日期,但此时我不知道如何通过在开始处添加分号进行编辑,或者删除满足条件的行
有什么建议吗?基本流程是:
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.
基本过程是:
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.
试试这个:
$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);
若要编辑该行,请使用preg_match并将编辑的行推送到新数组
如果要删除该行,请不要执行任何操作。别理他
如果要切换到下一行,请将当前行推送到新阵列
最后,将新数组保存到文件。尝试如下操作:
$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);
若要编辑该行,请使用preg_match并将编辑的行推送到新数组
如果要删除该行,请不要执行任何操作。别理他
如果要切换到下一行,请将当前行推送到新阵列
最后,将新数组保存到文件。我想:发现DBMS如果问题与DBMS有关,我甚至不会要求这样做。但是我正在做的项目包含一个文件中的数据。告诉项目经理或老师,她是个笨蛋,必须给你合适的工具。一个极端的解决方案是:1。如果处于低资源设置2,则将文件解析为DB check SQLite。详细说明如何使用新数据库3。设计一个具有所需格式4的DB导出例程?????5.利润我猜:发现DBMS如果问题与DBMS有关,我甚至不会要求这样做。但是我正在做的项目包含一个文件中的数据。告诉项目经理或老师,她是个笨蛋,必须给你合适的工具。一个极端的解决方案是:1。如果处于低资源设置2,则将文件解析为DB check SQLite。详细说明如何使用新数据库3。设计一个具有所需格式4的DB导出例程?????5.利润