Search code examples
phpsearchechotext-files

PHP to search within txt file and echo the whole line


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.


Solution

  • 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";
    }