2

如果从用户那里得到输入,我想在文件中搜索任何结果,并显示结果:

$searchValue = $_POST['search'];

$handle = @fopen("home.txt","r");
# read line by line
while (($buffer = fgets($handle, 4096)) !== false && // the condtion for the $searchValue) {
    echo '<tr>';
        $array = explode(',', $buffer);
    foreach($array as $val){
         echo '<td>'.$val.'</td>';      
        } 
    echo '</tr>';       
}

我没有得到我必须做的事情,我只想用相关的 $searchvalues 显示文本文件中的行

4

2 回答 2

1

我什至建议使用 file 命令:

array file  ( string $filename  [, int $flags = 0  [, resource $context  ]] )

读取文件,每行作为数组中的一个元素。从那里,您将迭代每一行(您提到返回文件中匹配的行,这就是我推荐 file(...) 的原因):

if (($fileLines = file('home.txt')) !== false)
{
  foreach ($fileLines as $line)
  {
    if (strpos($line, $searchVal) !== false)
    { // match found
      echo '<tr><td>'.str_replace(',','</td><td>',trim($line)).'</td></tr>';
    }
  }
}

仅仅为了重新加入它而爆炸阵列是没有用的。你也可以爆炸它然后用 </td><td> 来 implode() 它。

此外,您的文件似乎包含多行 CSV。如果是这种情况,您可能想要迭代每一行,然后对项目进行explode(...) 并在exploded 变量上执行in_array(...) (或使用strpos 迭代以再次进行部分匹配)。例如:

$values = explode(',',$line);
// array search (while entries)
if (in_array($searchVal,$values)) { ... }
// array search with partial matches
foreach ($values as $val) {
  if (strpos($val,$searchVal) !== false) { ... }
}
于 2010-11-04T13:53:47.427 回答
0

你正在寻找的是strpos()

int strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )

返回 haystack 字符串中第一次出现 needle 的数字位置。

以整数形式返回位置。如果没有找到 needle,strpos() 将返回布尔值 FALSE。

于 2010-11-04T13:21:59.207 回答