使用 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/