Home >Backend Development >PHP Tutorial >How to Find and Retrieve an Entire Line Containing Specific Data from a Text File Using PHP?

How to Find and Retrieve an Entire Line Containing Specific Data from a Text File Using PHP?

Linda Hamilton
Linda HamiltonOriginal
2024-11-19 22:52:02903browse

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:

  1. Open the Text File: Utilize file_get_contents(), ensuring that the file can be accessed and read.
  2. Prepare the Search Pattern: Escape special characters in the search string using preg_quote(). Then, create a regular expression pattern using preg_quote to match the entire line containing the search term.
  3. Search for Matching Lines: Employ preg_match_all() with the prepared pattern and the contents of the text file to retrieve all matching lines.
  4. Output the Matching Line: Iterate through the matches and echo the first match, which will represent the line containing "aullah1". The result will be displayed as "2 aullah1".

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn