PHP在文本文件中搜索并回显整行
使用php,我正在尝试创建一个脚本,该脚本将在文本文件中搜索并抓取整行并回显它。
我有一个标题为“ numorder.txt”的文本文件(.txt),该文本文件中有几行数据,每5分钟会有新行出现(使用cron作业)。 数据类似于:
2 aullah1
7 name
12 username
我将如何创建一个php脚本来搜索数据“ aullah1”,然后抓起整行并回显它? (一旦回显,它应该显示“ 2 aullah1”(不带引号)。
如果我没有清楚地解释任何事情和/或您希望我更详细地解释,请发表评论。
6个解决方案
69 votes
还有一个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";
}
Lekensteyn answered 2020-07-23T13:10:45Z
49 votes
像这样做。 这种方法使您可以搜索任何大小的文件(大文件不会使脚本崩溃),并将返回与所需字符串匹配的所有行。
$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);
?>
请注意!==与!==运算符一起使用的方式。
shamittomar answered 2020-07-23T13:11:10Z
20 votes
使用$found和$found:
// 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;
}
在此文件上进行测试时:
富扎
巴扎
阿布扎
它输出:
富扎
更新:
要显示文本(如果找不到该文本),请使用如下所示的内容:
$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变量来查找是否找到匹配项。
Frxstrem answered 2020-07-23T13:12:09Z
4 votes
看起来您最好将其系统化为system("grep \"$QUERY\""),因为无论哪种方式该脚本都不会具有很高的性能。 否则,[http://php.net/manual/en/function.file.php]向您展示了如何循环显示行,您可以使用[http://php.net/manual/en/function.strstr.php] 寻找比赛。
Novikov answered 2020-07-23T13:12:29Z
3 votes
// script.php
$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:
";
echo implode("
", $matches[0]);
}
else{
echo "No matches found";
fclose ($file);
}
?>
answered 2020-07-23T13:12:45Z
2 votes
单程...
$needle = "blah";
$content = file_get_contents('file.txt');
preg_match('~^(.*'.$needle.'.*)$~',$content,$line);
echo $line[1];
尽管最好用fopen()和fread()逐行读取并使用strpos()可能会更好
Crayon Violent answered 2020-07-23T13:13:09Z