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

标签 php search echo text-files

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

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

2 aullah1
7 name
12 username

我将如何创建一个 php 脚本来搜索数据“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";
}

关于PHP 在 txt 文件中搜索并回显整行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3686177/

相关文章:

ios - UITextView如何实现搜索功能?

git - 直接从 git shell 添加文件到 .gitignore

javascript - "Unhandled Rejection (SyntaxError): Unexpected token h in JSON at position 0"与response.json()

php - 以编程方式更新 WordPress 帖子摘录

php - Laravel 和 Paypal

java - Java中最快的子串搜索方法是什么

php - excel array column double/triple/etc..辅音生成

java - 当用户开始输入时滚动/​​搜索 JList

如果 $post 存在,PHP 基本回显

bash - 管道回显时抑制输出到 StdOut