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.
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.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.one way...
though it would probably be better to read it line by line with fopen() and fread() and use strpos()
And a PHP example, multiple matching lines will be displayed:
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.