在一个txt文件中搜索多个字符串


Searching multiple strings in one txt file

我知道还有很多其他答案,但它们不适合我的代码。由于代码,我每次搜索都要处理1000行以上。

我想组合两个输入的字符串,这样PHP脚本就可以在txt文件中搜索这两个输入,并在输出时组合它们。

这就是我尝试的:

$search = $_GET["search"]; 
$search2 = $_GET['search2'];
$logfile = $_GET['logfile'];

// Read from file 
$file = fopen($logfile, "r");?> 
<head><title>Searching: <?php echo $search ?></title></head>
<?php
while( ($line =  fgets($file) && $line2 = fgets($file))!= false)
{   if (stristr($line, $search)) { } if (stristr($line2, $search2)) { }  
?><font face='Arial'> <?php $lines = $line + line2; ?><?php echo $lines ?></font><hr><p><?php
}

当我在填写search和search2的情况下运行此代码时:我得到了以下输出:

1
1
1
1
1
1

而这1似乎是无限的。我希望任何人都能找到解决方案。

两个字符串的输出都应为:search="新">

He is a new player
Gambling is a new sport
New is better than old

search2="网站">

It is a nice website
The website is down
The FIFA website is being built

正确的输出应该是:

He is a new player
It is a nice website
Gambling is a new sport
The FIFA website is being built
New is better than old

感谢您的阅读。

~ Conner

<?php 
$search1 = "value 1"; 
$search2 = "value 2";
$lines = file('my_file.txt'); 
foreach($lines as $line) 
{ 
    if(stristr($line,$search1) || stristr($line,$search2))
        echo " $line <br>"; 
} 
?>

请查看此代码是否有效。这将为您提供$search1$search2出现的行。谢谢:(

您可以尝试以下操作:

foreach (new SplFileObject($logfile) as $lineNumber => $lineContent) {
    if(strpos($lineContent, $search) !== false
       || strpos($lineContent, $search2) !== false
    ) {
        echo $lineContent . '<br />';
    }
}