搜索 txt 文件的最佳方法是什么,在 php 中显示页面上的所有结果


What would be the best way to search a txt file display all result on page in php

我一直在尝试创建一个页面,您可以在其中仅使用html和php搜索.txt文件。

这是我的代码:

<?php
$file = 'myfile.txt';
if (preg_match_all($pattern, $contents, $matches)) {
   echo "Found matches:'n";
   echo implode("'n", $matches[0]);
}
else {
  echo "No matches found";
}

请尝试此代码。您的代码丢失$contents

<?php
$file = 'somefile.txt';
$searchfor = 'search text would come here';
// get the file contents
$contents = file_get_contents($file);
// escape special characters in the query
$pattern = preg_quote($searchfor, '/');
// regular expression
$pattern = "/^.*$pattern.*'$/m";
// search
if(preg_match_all($pattern, $contents, $matches)){
   echo "Found matches:'n";
   echo implode("'n", $matches[0]);
}
else{
   echo "No matches found";
}

谢谢阿米特