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

发布于 2024-09-18 05:57:28 字数 316 浏览 5 评论 0原文

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

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

2 aullah1
7 name
12 username

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

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

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

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:

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).

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

献世佛 2024-09-25 05:57:28

以 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";
}

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

<?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";
}
情深缘浅 2024-09-25 05:57:28

像这样做。这种方法允许您搜索任意大小的文件(大文件不会使脚本崩溃),并将返回与您想要的字符串匹配的所有行

<?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!== 运算符一起使用的方式。

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 match the 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 strpos is used with !== operator.

笑,眼淚并存 2024-09-25 05:57:28

使用 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;
}

对此文件进行测试时:

福扎
巴尔扎
abczah

它输出:

福扎


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

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

这里我使用 $found 变量来查找是否找到匹配项。

Using file() and 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 $found variable to find out if a match was found.

柒夜笙歌凉 2024-09-25 05:57:28
$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); 
}
$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); 
}
黑寡妇 2024-09-25 05:57:28

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

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.php shows you how to loop over lines and you can use http://php.net/manual/en/function.strstr.php for finding matches.

兮子 2024-09-25 05:57:28

一种方式...

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

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

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()

陌上芳菲 2024-09-25 05:57:28

对已投票答案的方法进行了稍微修改,以通过 GET 变量支持多个目录和变量关键字(如果您希望这样做)

if (isset($_GET["keyword"])){

   foreach(glob('*.php') as $file) { 

      $searchfor = $_GET["keyword"];
      
      // 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 $file. "\n";
         echo implode("\n", $matches[0]);
         echo "\n\n";
      }
      else{
      //  echo "No matches found";
      }
   }
}

Slightly modified approach of the Upvoted answer to support multiple directories and variable keywords through a GET variable (if you wish to do it that way)

if (isset($_GET["keyword"])){

   foreach(glob('*.php') as $file) { 

      $searchfor = $_GET["keyword"];
      
      // 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 $file. "\n";
         echo implode("\n", $matches[0]);
         echo "\n\n";
      }
      else{
      //  echo "No matches found";
      }
   }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文