1

我正在尝试在文本文件中搜索一行中的两个值。如果两个值都存在,我需要输出整行。我正在搜索的值可能不会彼此相邻,这就是我卡住的地方。我有以下代码运行良好,但仅适用于一个搜索值:

<?php 
$search = $_REQUEST["search"]; 
// Read from file 
$lines = file('archive.txt'); 
foreach($lines as $line) 
{ 
// Check if the line contains the string we're looking for, and print if it does 
if(strpos($line, $search) !== false) 
echo"<html><title>SEARCH RESULTS FOR: $search</title><font face='Arial'> $line <hr>"; 
} 

?>

非常感谢任何帮助。提前谢谢了。

4

4 回答 4

4

假设您要搜索的值由空格分隔,并且它们都将始终存在,explode应该可以解决问题:

$search = explode(' ', $_REQUEST["search"]);  // change ' ' to ',' if you separate the search terms with a comma, etc.
// Read from file 
$lines = file('archive.txt'); 
foreach($lines as $line) 
{ 
    // Check if the line contains the string we're looking for, and print if it does 
    if(strpos($line, $search[0]) !== false && strpos($line, $search[1] !== false)) { 
        echo"<html><title>SEARCH RESULTS FOR: $search</title><font face='Arial'> $line <hr>";
    }
} 

我将由您来添加一些验证,以确保$search数组中始终有两个元素,等等。

于 2012-11-09T01:16:43.917 回答
3

我还更正了 HTML 代码。该脚本查找两个值,$search$search2. 它正在使用stristr()。对于 strstr 的区分大小写版本,请参阅strstr()。该脚本将返回包含$search和的所有行$search2

<?php 
$search = $_REQUEST["search"]; 
$search2 = $_REQUEST['search2'];
// Read from file 
$lines = file('archive.txt'); 
echo"<html><head><title>SEARCH RESULTS FOR: $search</title></head><body>";
foreach($lines as $line) 
{ 
// Check if the line contains the string we're looking for, and print if it does 
if(stristr($line,$search) && stristr($line,$search2))  // case insensitive
    echo "<font face='Arial'> $line </font><hr>"; 
} 
?>
</body></html>
于 2012-11-09T01:15:10.103 回答
1

只需搜索您的其他值并使用 && 来检查两者。

      <?php 
        $search1 = $_REQUEST["search1"];
         $search2 = $_REQUEST["search2"];
        // Read from file 
         $lines = file('archive.txt'); 
        foreach($lines as $line) 
        { 
           // Check if the line contains the string we're looking for, and print if it does 
          if(strpos($line, $search1) !== false && strpos($line, $search2) !== false) 
             echo"<html><title>SEARCH RESULTS FOR: $search1 and $search2</title><font face='Arial'> $line <hr>"; 
        } 

       ?>
于 2012-11-09T01:17:27.927 回答
0

这对我有用。您可以在 searchthis 数组中定义您喜欢的内容,它将以整行显示。

<?php
$searchthis = array('1','2','3');
$matches = array();

$handle = fopen("file_path", "r");
if ($handle)
{
while (!feof($handle))
{
    $buffer = fgets($handle);

    foreach ($searchthis as $param) {
    if(strpos($buffer, $param) !== FALSE)
        $matches[] = $buffer;
 }}
 fclose($handle);
 }

 foreach ($matches as $parts) {
echo $parts;
}
?>
于 2017-12-08T15:18:47.373 回答