PHP在txt文件内search并回显整个行

使用PHP,我试图创build一个脚本,将在一个文本文件中search,并抓住整条线,并呼应它。

我有一个名为“numorder.txt”的文本文件(.txt),在该文本文件中,有几行数据,每5分钟有一行新行(使用cron作业)。 数据看起来类似于:

2 aullah1 7 name 12 username 

我将如何去创build一个PHP脚本,将search数据“aullah1”,然后抓住整个线路,并呼应它? (一旦回声,应显示“2 aullah1”(不含引号)。

如果我没有解释清楚和/或你想我更详细地解释,请评论。

而一个PHP的例子,会显示多个匹配的行:

 <?php $file = 'somefile.txt'; $searchfor = 'name'; // the following line prevents the browser from parsing this as HTML. header('Content-Type: text/plain'); // get the file contents, assuming the file to be readable (and exist) $contents = file_get_contents($file); // escape special characters in the query $pattern = preg_quote($searchfor, '/'); // finalise the regular expression, matching the whole line $pattern = "/^.*$pattern.*\$/m"; // search, and store all matching occurences in $matches if(preg_match_all($pattern, $contents, $matches)){ echo "Found matches:\n"; echo implode("\n", $matches[0]); } else{ echo "No matches found"; } 

像这样做。 这种方法可以让你search任何大小文件 (大尺寸不会使脚本崩溃),并且会返回所有与你想要的string匹配

 <?php $searchthis = "mystring"; $matches = array(); $handle = @fopen("path/to/inputfile.txt", "r"); if ($handle) { while (!feof($handle)) { $buffer = fgets($handle); if(strpos($buffer, $searchthis) !== FALSE) $matches[] = $buffer; } fclose($handle); } //show results: print_r($matches); ?> 

注意strpos!==运算符一起使用的方式。

使用file()strpos()

 <?php // What to look for $search = 'foo'; // Read from file $lines = file('file.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 $line; } 

在此文件上testing时:

foozah
barzah
abczah

它输出:

foozah


更新:
要显示文本,如果没有find文本,使用这样的东西:

 <?php $search = 'foo'; $lines = file('file.txt'); // Store true when the text is found $found = false; foreach($lines as $line) { if(strpos($line, $search) !== false) { $found = true; echo $line; } } // If the text was not found, show a message if(!$found) { echo 'No match found'; } 

在这里,我使用$foundvariables来找出是否find了匹配。

看起来像你最好系统化到system("grep \"$QUERY\"")因为该脚本将不会是特别高的性能方式。 否则, http://php.net/manual/en/function.file.php会告诉你如何遍历行,你可以使用http://php.net/manual/en/function.strstr.php来查找匹配。;

单程…

 $needle = "blah"; $content = file_get_contents('file.txt'); preg_match('~^(.*'.$needle.'.*)$~',$content,$line); echo $line[1]; 

尽pipe用fopen()和fread()逐行读取并使用strpos()会更好。

  <?php // script.php $searchfor = $_GET['keyword']; $file = 'users.txt'; $contents = file_get_contents($file); $pattern = preg_quote($searchfor, '/'); $pattern = "/^.*$pattern.*\$/m"; if(preg_match_all($pattern, $contents, $matches)){ echo "Found matches:<br />"; echo implode("<br />", $matches[0]); } else{ echo "No matches found"; fclose ($file); } ?>