PHP在txt文件中搜索并回显整行
使用 php,我尝试创建一个脚本,该脚本将在文本文件中搜索并抓取整行并回显它。
我有一个标题为“numorder.txt”的文本文件 (.txt),在该文本文件中,有几行数据,每 5 分钟就会有新行出现(使用 cron 作业)。数据看起来类似于:
2 aullah1
7 name
12 username
我将如何创建一个 php 脚本来搜索数据“aullah1”,然后抓取整行并回显它? (一旦回显,它应该显示“2 aullah1”(不带引号)。
如果我没有清楚地解释任何内容和/或您希望我更详细地解释,请发表评论。
Using php, I'm trying to create a script which will search within a text file and grab that entire line and echo it.
I have a text file (.txt) titled "numorder.txt" and within that text file, there are several lines of data, with new lines coming in every 5 minutes (using cron job). The data looks similar to:
2 aullah1
7 name
12 username
How would I go about creating a php script which will search for the data "aullah1" and then grab the entire line and echo it? (Once echoed, it should display "2 aullah1" (without quotations).
If I didn't explain anything clearly and/or you'd like me to explain in more detail, please comment.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
以 PHP 为例,会显示多条匹配行:
And a PHP example, multiple matching lines will be displayed:
像这样做。这种方法允许您搜索任意大小的文件(大文件不会使脚本崩溃),并将返回与您想要的字符串匹配的所有行。
请注意
strpos
与!==
运算符一起使用的方式。Do it like this. This approach lets you search a file of any size (big size won't crash the script) and will return ALL lines that match the string you want.
Note the way
strpos
is used with!==
operator.使用
file()
和strpos()
:对此文件进行测试时:
它输出:
更新:
要在未找到文本时显示文本,请使用如下内容:
这里我使用
$found
变量来查找是否找到匹配项。Using
file()
andstrpos()
:When tested on this file:
It outputs:
Update:
To show text if the text is not found, use something like this:
Here I'm using the
$found
variable to find out if a match was found.看起来您最好将系统输出到
system("grep \"$QUERY\"")
因为该脚本无论如何都不会具有特别高的性能。否则 http://php.net/manual/en/function.file.php 向您展示如何循环行,您可以使用 http://php.net /manual/en/function.strstr.php 用于查找匹配项。looks like you're better off systeming out to
system("grep \"$QUERY\"")
since that script won't be particularly high performance either way. Otherwise http://php.net/manual/en/function.file.php shows you how to loop over lines and you can use http://php.net/manual/en/function.strstr.php for finding matches.一种方式...
尽管使用 fopen() 和 fread() 逐行读取它并使用 strpos() 可能会更好
one way...
though it would probably be better to read it line by line with fopen() and fread() and use strpos()
对已投票答案的方法进行了稍微修改,以通过 GET 变量支持多个目录和变量关键字(如果您希望这样做)
Slightly modified approach of the Upvoted answer to support multiple directories and variable keywords through a GET variable (if you wish to do it that way)