如何用php搜索txt文件的特定行
我将文章中的数据存储在.txt文件中。 txt文件如下所示:如何用php搜索txt文件的特定行,php,arrays,file,search,feof,Php,Arrays,File,Search,Feof,我将文章中的数据存储在.txt文件中。 txt文件如下所示: id_20201010120010 // id of article Sport // category of article data/uploads/image-1602324010_resized.jpg // image of article Champions League
id_20201010120010 // id of article
Sport // category of article
data/uploads/image-1602324010_resized.jpg // image of article
Champions League // title of article
Nunc porttitor ut augue sit amet maximus... // content of the article
2020-10-10 12:00 // date article
John // author of article
oPXWlZp+op7B0+/v5Y9khQ== // encrypted email of author
football,soccer // tags of article
true // boolean (SHOULD BE IGNORED WHEN SEARCHING)
false // boolean (SHOULD BE IGNORED WHEN SEARCHING)
要在文章中搜索,请使用以下代码:
$searchthis = strtolower('Nunc');
$searchmatches = [];
foreach($articles as $article) { // Loop through all the articles
$handle = @fopen($article, "r");
if ($handle) {
while (!feof($handle)) {
$buffer = fgets($handle);
if(strpos(strtolower($buffer), $searchthis) !== FALSE) { // strtolower; search word not case sensitive
$searchmatches[] = $article; // array of articles with search matches
}
}
fclose($handle);
}
}
//show results:
if(empty($searchmatches)) { // if empty array
echo 'no match found';
}
print_r($searchmatches);
这一切都很好!但是当搜索像
true
这样的词时,他几乎找到了所有的文章,因为在所有的文章中,最后一行是两个布尔值。那么,如何从搜索中跳过txt文件的最后两行呢?一种方法是将整个文件读入一个数组,然后从数组中去掉最后两个元素。然后,您可以遍历数组以查找搜索值。注意:您可以使用执行不区分大小写的搜索:
foreach ($articles as $article) {
$data = file($article);
if ($data === false) continue;
$data = array_slice($data, 0, -2);
$search = 'league';
foreach ($data as $value) {
if (stripos($value, $search) !== false) {
$searchmatches[] = $article;
}
}
}
一种方法是将整个文件读入数组,然后从数组中去掉最后两个元素。然后,您可以遍历数组以查找搜索值。注意:您可以使用执行不区分大小写的搜索:
foreach ($articles as $article) {
$data = file($article);
if ($data === false) continue;
$data = array_slice($data, 0, -2);
$search = 'league';
foreach ($data as $value) {
if (stripos($value, $search) !== false) {
$searchmatches[] = $article;
}
}
}
要读取文件,请使用
file()
函数,而不是像某些C代码那样使用fopen
、fgets
等。它将读取所有文件并将其放入一个行数组中。然后选择要进行搜索的行
要读取文件,请使用file()
函数,而不是像某些C代码那样使用fopen
、fgets
等。它将读取所有文件并将其放入一个行数组中。然后选择要进行搜索的行
@john不用担心-我很高兴我能帮上忙。@john不用担心-我很高兴我能帮上忙。我写的答案可能与Nick的时间相同!stackoverflow总是存在同样的问题。但是把你所有的文章放进数据库不是更有效吗?这些文件可能是历史性的选择。但把它们推到数据库中并不晚。我想如果你以后必须添加或更改一些属性,那会容易得多。我可能在同一时间写了一个答案,而不是尼克!stackoverflow总是存在同样的问题。但是把你所有的文章放进数据库不是更有效吗?这些文件可能是历史性的选择。但把它们推到数据库中并不晚。我认为,如果您以后必须添加或更改某些属性,这将容易得多。