Home >Backend Development >PHP Tutorial >How Can I Find and Display Specific Lines from a Text File Using PHP?

How Can I Find and Display Specific Lines from a Text File Using PHP?

Barbara Streisand
Barbara StreisandOriginal
2024-11-23 21:20:11273browse

How Can I Find and Display Specific Lines from a Text File Using PHP?

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 file_get_contents function reads the text file's contents into a variable.
  • The preg_quote function escapes special characters in the search phrase, ensuring that it's treated as a literal string.
  • The regular expression /^.*$pattern.*$/m matches the entire line containing the search phrase ($pattern). The m flag enables multi-line search.
  • The preg_match_all function performs the search, storing any matches in the $matches array.
  • The matches are then displayed by iterating over the $matches[0] array, which contains the entire matching lines.

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!

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