PHP在txt文件中搜索并回显整行 [英] PHP to search within txt file and echo the whole line

查看:265
本文介绍了PHP在txt文件中搜索并回显整行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Using php, I'm trying to create a script which will search within a text file and grab that entire line and echo it.

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

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

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

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.

推荐答案

以一个PHP示例为例,将显示多行匹配:

And a PHP example, multiple matching lines will be displayed:

<?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文件中搜索并回显整行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆