好的,我之前有个问题。
我发现了如何使用基于unix时间的php删除txt文件中的行
这是我当前的代码。
<?php
$output = array();
$lines = file('file.txt');
$now = time();
foreach ($lines as $line) {
list($content, $time) = explode("|", $line);
if ($time > $now) {
$output[] = $line;
}
}
$outstring = implode($output);
file_put_contents("file.txt", $outstring);
print time();
?>
该代码的作用是,文件中的每个条目在Unix 中都有一个时间
所以
它的设置就像这个
Content | Unix Time
Content | Unix Time
我想做的是用一个PHRASE或WORD来代替unix时间,这表明行需要保持在那里。
有片段吗?或者这会很难吗?
如有任何帮助,我们将不胜感激。
添加
$keepStr = "KEEP";
在顶部,并将foreach
循环替换为:
foreach ($lines as $line) {
list($content, $value) = explode("|", $line);
if ($value == $keepStr || $value > time() ) {
$output[] = $line;
}
}
将转换
Content1 | KEEP
Content2 | Somevalue
Content3 | Someothervalue
Content4 | KEEP
至
Content1 | KEEP
Content4 | KEEP
您可以通过更改给定给$keepStr
的值来定义要保留的字符串
看看我之前在你的帖子上发布了什么(供参考)。通过更改if
语句中的条件,可以很容易地做到这一点。(其他解决方案也是如此,看看我在if
语句中更改了什么)。
使用我之前发布的代码进行了一些修改:
<?php
$whiteword = "keep";
$filtered = array();
if($handle = fopen("file.txt", "r")){
while($data = fgetcsv($handle, 0, "|")){
if($data[1] === $whiteword || $data[1] > time()){
$filtered[] = $data;
}
}
fclose($handle);
}
if($handle = fopen("file.txt", "w")){
for($i = 0; $i < count($filtered); $i += 1){
fputcsv($handle, $filtered[$i], "|");
}
}
?>