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

问题描述 投票:0回答:8

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

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

2 aullah1
7 name
12 username

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

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

php search echo text-files
8个回答
91
投票

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

61
投票

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

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

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


26
投票
使用

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

 变量来查找是否找到匹配项。


10
投票
$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); }
    

4
投票
看起来您最好将其系统化为

system("grep \"$QUERY\"")

,因为该脚本无论如何都不会具有特别高的性能。否则 
http://php.net/manual/en/function.file.php 向您展示如何循环行,您可以使用 http://php.net/manual/en/function.strstr.php用于查找匹配项。


3
投票
单向...

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

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


0
投票
稍微修改了已投票答案的方法,以通过 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"; } } }
    

0
投票
<?php // Specify the directory path where you want to search for .txt files. $directory = '/path/to/your/folder/'; // Define the search text as a variable. $searchText = 'sample'; // Open the directory for reading. $dir = opendir($directory); // Loop through the directory's contents. while (false !== ($file = readdir($dir))) { // Check if the file has a .txt extension. if (pathinfo($file, PATHINFO_EXTENSION) === 'txt') { // Read the contents of the file. $content = file_get_contents($directory . $file); // Split the file content into an array of lines. $lines = explode("\n", $content); // Loop through each line and check if it contains the search text. foreach ($lines as $line) { if (strpos($line, $searchText) !== false) { echo "Matched line in file $file: $line\n"; } } } } // Close the directory. closedir($dir); ?>
    
© www.soinside.com 2019 - 2024. All rights reserved.