Home >Backend Development >PHP Tutorial >How to Find and Retrieve an Entire Line Containing Specific Data from a Text File Using PHP?
Searching and Retrieving Entire Lines from a Text File in PHP
In this scenario, you aim to create a PHP script that identifies a specific data within a text file ("numorder.txt") and outputs the complete line containing that data. Specifically, you seek to search for "aullah1" and display the corresponding line, which should appear as "2 aullah1".
To achieve this, follow these steps:
Here's a code example demonstrating these steps:
$file = 'numorder.txt'; $searchfor = 'aullah1'; header('Content-Type: text/plain'); $contents = file_get_contents($file); $pattern = preg_quote($searchfor, '/'); $pattern = "/^.*$pattern.*$/m"; if (preg_match_all($pattern, $contents, $matches)) { echo "Found matches:\n"; echo implode("\n", $matches[0]); } else { echo "No matches found"; } ?>
This script will search the "numorder.txt" file for "aullah1" and output the entire line containing that data, displaying "2 aullah1" as the result.
The above is the detailed content of How to Find and Retrieve an Entire Line Containing Specific Data from a Text File Using PHP?. For more information, please follow other related articles on the PHP Chinese website!