php PHP在txt文件中搜索并回显整行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3686177/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 10:42:01  来源:igfitidea点击:

PHP to search within txt file and echo the whole line

phpsearchechotext-files

提问by aullah

Using php, I'm trying to create a script which will search within a text file and grab that entire line and echo it.

使用 php,我正在尝试创建一个脚本,该脚本将在文本文件中搜索并抓取整行并回显它。

I have a text file (.txt) titled "numorder.txt" and within that text file, there are several lines of data, with new lines coming in every 5 minutes (using cron job). The data looks similar to:

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

2 aullah1
7 name
12 username

How would I go about creating a php script which will search for the data "aullah1" and then grab the entire line and echo it? (Once echoed, it should display "2 aullah1" (without quotations).

我将如何创建一个 php 脚本来搜索数据“aullah1”,然后抓取整行并回显它?(一旦回显,它应该显示“2 aullah1”(不带引号)。

If I didn't explain anything clearly and/or you'd like me to explain in more detail, please comment.

如果我没有解释清楚和/或您希望我更详细地解释,请发表评论。

回答by Lekensteyn

And a PHP example, multiple matching lines will be displayed:

和一个 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";
}

回答by shamittomar

Do it like this. This approach lets you search a file of any size(big size won't crash the script) and will return ALL lines that matchthe string you want.

像这样做。这种方法使您可以搜索任何大小文件(大尺寸不会使脚本崩溃)并返回您想要的字符串匹配所有行

<?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);
?>

Note the way strposis used with !==operator.

请注意,该方式strpos!==运算符一起使用。

回答by Frxstrem

Using file()and 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;
}

When tested on this file:

在此文件上测试时:

foozah
barzah
abczah

福扎·
巴尔扎·
阿布扎赫

It outputs:

它输出:

foozah

福扎



Update:
To show text if the text is not found, use something like this:

更新:
要在找不到文本时显示文本,请使用以下内容:

<?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';
}

Here I'm using the $foundvariable to find out if a match was found.

在这里,我使用$found变量来确定是否找到了匹配项。

回答by Frxstrem

 <?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); 
         }
       ?>

回答by Novikov

looks like you're better off systeming out to system("grep \"$QUERY\"")since that script won't be particularly high performance either way. Otherwise http://php.net/manual/en/function.file.phpshows you how to loop over lines and you can use http://php.net/manual/en/function.strstr.phpfor finding matches.

看起来你最好system("grep \"$QUERY\"")不要系统化,因为无论哪种方式,该脚本的性能都不会特别高。否则http://php.net/manual/en/function.file.php向您展示如何循环遍历行,您可以使用http://php.net/manual/en/function.strstr.php查找匹配项。

回答by Crayon Violent

one way...

单程...

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

though it would probably be better to read it line by line with fopen() and fread() and use strpos()

尽管使用 fopen() 和 fread() 逐行阅读它并使用 strpos() 可能会更好