【发布时间】:2020-02-21 21:43:47
【问题描述】:
我在文件夹 messages 中有一些 .txt 文件。
每个文件有 6 行。我的文件是这样的:
id_20197456 // identity
Friends //category
Test // title
10 Feb 2020 22:28 // date
John // writer
Lorum ipsum.... // message
类别名称总是在第2行行
我总共有 5 个文件:4 类别为 Friends 和 1 类别为 Offside。
现在我想删除类别为Offside的文件
这是我目前所拥有的,用于捕获类别为 Offside 的文件:
$filterthis = strtolower('Offside');
$newslist = array();
$files = glob("messages/*.txt"); // Specify the file directory by extension (.txt)
foreach($files as $file) { // Loop through the files in the directory
$handle = @fopen($file, "r");
if ($handle) {
$lines = file($file); //file into an array
$buffer = $lines[1]; // grab category line
if(strpos(strtolower($buffer), $filterthis) !== FALSE) { // strtolower; search word not case sensitive
$newslist[] = $file; // The filename of the match
// below the file which has Offside category
print_r($newslist); // outputs: Array ( [0] => messages/id_20200210222825.txt )
}
fclose($handle);
}
}
为了输出所有文件,我使用了一个 foreach 循环:
foreach($newslist as $file) {
$lines = file($file, FILE_IGNORE_NEW_LINES); // filedata into an array
$file_id = $lines[0]; // file id
$news_category = $lines[1]; // news category
$news_title = $lines[2]; // news title
$news_date = $lines[3]; // news date
$news_author = $lines[4]; // author name
$news_message = $lines[5]; // news message
fclose($fh);
// all the echos's come here...
}
我的问题:我如何过滤在 foreach 中没有 Offside 作为类别的文件?
所以foreach应该输出除了Offside类别的所有文件吗?
【问题讨论】:
-
不能进行简单的字符串比较吗?
-
我想你需要的只是改变比较。使用
if(strpos(strtolower($buffer), $filterthis) === false) {,然后添加所有没有您选择的类别的文件。如果您需要这两个信息,或者使用不同的数组。