How Can I Use PHP to Find and Display Entire Lines Containing a Specific String in a Text File?

Mary-Kate Olsen
Release: 2024-11-22 06:02:13
Original
442 people have browsed it

How Can I Use PHP to Find and Display Entire Lines Containing a Specific String in a Text File?

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);
Copy after login

Here, we obtain the file contents and store them in the $contents variable.

2. Regular Expression (Regex):

$pattern = preg_quote($searchfor, '/');
$pattern = '/^.*' . $pattern . '.*$/m';
Copy after login

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

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!

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