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

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


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


2 aullah1

7 name

12 username

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


如果我没有清楚地解释任何事情和/或您想让我更详细地解释,请发表评论。


哆啦的时光机
浏览 850回答 3
3回答

心有法竹

还有一个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 $matchesif(preg_match_all($pattern, $contents, $matches)){&nbsp; &nbsp;echo "Found matches:\n";&nbsp; &nbsp;echo implode("\n", $matches[0]);}else{&nbsp; &nbsp;echo "No matches found";}

小唯快跑啊

像这样做。这种方法可以让你搜索一个任意大小的文件(大尺寸不会崩溃的脚本),并返回匹配的所有行你想要的字符串。<?php$searchthis = "mystring";$matches = array();$handle = @fopen("path/to/inputfile.txt", "r");if ($handle){&nbsp; &nbsp; while (!feof($handle))&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; $buffer = fgets($handle);&nbsp; &nbsp; &nbsp; &nbsp; if(strpos($buffer, $searchthis) !== FALSE)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $matches[] = $buffer;&nbsp; &nbsp; }&nbsp; &nbsp; fclose($handle);}//show results:print_r($matches);?>注意,该方法strpos与!==运算符一起使用。

尚方宝剑之说

使用file()和strpos():<?php// What to look for$search = 'foo';// Read from file$lines = file('file.txt');foreach($lines as $line){&nbsp; // Check if the line contains the string we're looking for, and print if it does&nbsp; if(strpos($line, $search) !== false)&nbsp; &nbsp; echo $line;}在此文件上进行测试时:foozah&nbsp;barzah&nbsp;abczah它输出:富扎更新:如果未找到文本,则显示文本,请使用类似以下内容的方法:<?php$search = 'foo';$lines = file('file.txt');// Store true when the text is found$found = false;foreach($lines as $line){&nbsp; if(strpos($line, $search) !== false)&nbsp; {&nbsp; &nbsp; $found = true;&nbsp; &nbsp; echo $line;&nbsp; }}// If the text was not found, show a messageif(!$found){&nbsp; echo 'No match found';}在这里,我使用$found变量来查找是否找到匹配项。
打开App,查看更多内容
随时随地看视频慕课网APP