Searching and Echoing Entire Lines from a TXT File in PHP
The task at hand is to develop a PHP script capable of searching a text file (.txt) for a specific string and retrieving the entire line containing that string. Let's break down the solution:
1. File Handling:
$file = 'numorder.txt'; $searchfor = 'aullah1'; $contents = file_get_contents($file);
Here, we obtain the file contents and store them in the $contents variable.
2. Regular Expression (Regex):
$pattern = preg_quote($searchfor, '/'); $pattern = '/^.*' . $pattern . '.*$/m';
We construct a regex pattern that ensures we match the entire line containing the search string (aullah1) using preg_quote and preg_match_all. preg_quote escapes special characters in the search string to ensure it's handled literally by the regex.
3. Searching and Output:
if (preg_match_all($pattern, $contents, $matches)) { echo implode("\n", $matches[0]); } else { echo "No matches found"; }
If matches are found, the script will echo each matching line separated by newlines. Otherwise, it will display "No matches found."
By following these steps, you can create a PHP script that successfully searches within a text file and retrieves the entire line containing the specified data.
The above is the detailed content of How Can I Use PHP to Find and Display Entire Lines Containing a Specific String in a Text File?. For more information, please follow other related articles on the PHP Chinese website!