如何在 PHP 中搜索文件并返回结果和行号数组


How do I search a file and return an array of the results and line number in PHP?

如何搜索文件并返回结果数组,以便我可以在 PHP 的集合中使用它?

例如,假设我有一个.txt文件,其中包含以下内容:

hellohello
hihi
heywhats up
hello hey whats up
hello

我想搜索所有带有hello及其行号的出现,然后将其作为数组返回,以便我可以在数据收集器中使用它。

因此,它将返回行号和行,如下所示:

$results = array
(
array('1', 'hellohello'), 
array('4', 'hello hey whats up'), 
array('5', 'hello'),
);

我的想法对我们来说是file_get_contents.

所以,例如..

$file = 'example.txt';
function get_file($file) {
  $file = file_get_contents($file);
  return $file;
}
function searchFile($search_str) {
  $matches = preg_match('/$search_str/i', get_file($file);
  return $matches;
}

作为替代方案,您也可以使用 file() 函数,以便它将整个文件读取到数组中。然后你可以循环,然后搜索。粗略的例子:

$file = 'example.txt';
$search = 'hello';
$results = array();
$contents = file($file);
foreach($contents as $line => $text) {
    if(stripos($text, $search) !== false) {
        $results[] = array($line+1, $text);
    }
}
print_r($results);

旁注:stripos()只是一个例子,您仍然可以使用其他方式/偏好在针上搜索该特定线。