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

AUl*_*ah1 43 php search echo text-files

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

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

2 aullah1
7 name
12 username
Run Code Online (Sandbox Code Playgroud)

我将如何创建一个PHP脚本,它将搜索数据"aullah1",然后抓住整行并回显它?(一旦回应,它应显示"2 aullah1"(不带引号).

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

Lek*_*eyn 71

还有一个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";
}
Run Code Online (Sandbox Code Playgroud)

  • 你是说`preg_match_all`吗? (3认同)
  • 是的我做了,我习惯了JS'g'标志:使用一个函数:o (2认同)

sha*_*mar 50

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

<?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);
?>
Run Code Online (Sandbox Code Playgroud)

注意该方法strpos!==操作员一起使用.

  • 我唯一要吃的牛肉就是抑制错误。*我认为*,最好在生产时关闭display_errors,但至少这样,您就可以看到任何错误并可以在开发过程中修复它们。+1虽然是个不错的答案。 (2认同)

Frx*_*rem 20

使用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;
}
Run Code Online (Sandbox Code Playgroud)

在此文件上测试时:

foozah
barzah
abczah

它输出:

foozah


更新:
要显示未找到文本的文本,请使用以下内容:

<?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';
}
Run Code Online (Sandbox Code Playgroud)

在这里,我使用$found变量来查明是否找到了匹配项.


小智 8

$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); 
}
Run Code Online (Sandbox Code Playgroud)