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

Barbara Streisand
Release: 2024-11-23 21:20:11
Original
193 people have browsed it

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";
}
?>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template