Finding Specific Lines in a Text File Using PHP
Scenario:
You have a text file containing multi-line data that is updated periodically. You need to search the file for a specific piece of data and display the entire corresponding line.
Solution:
To search within a text file and retrieve the entire matching line, follow these steps using PHP:
<?php $file = 'numorder.txt'; $searchfor = 'aullah1'; // Disable HTML parsing header('Content-Type: text/plain'); // Read the file contents $contents = file_get_contents($file); // Escape special characters in the search phrase $pattern = preg_quote($searchfor, '/'); // Create a regular expression to match the entire line $pattern = "/^.*$pattern.*$/m"; // Perform the search if (preg_match_all($pattern, $contents, $matches)) { echo "Found matches:\n"; echo implode("\n", $matches[0]); } else { echo "No matches found"; } ?>
Explanation:
The above is the detailed content of How Can I Find and Display Specific Lines from a Text File Using PHP?. For more information, please follow other related articles on the PHP Chinese website!