Home  >  Article  >  Backend Development  >  How to Determine if a File Contains a Specific String in PHP?

How to Determine if a File Contains a Specific String in PHP?

DDD
DDDOriginal
2024-10-23 19:39:02908browse

How to Determine if a File Contains a Specific String in PHP?

PHP: Determining if a File Contains a Specified String

In PHP, you can utilize various approaches to check if a file contains a particular string. One common method involves iterating over the file's content line by line and searching for the string using strpos(). However, you may encounter issues with this approach as demonstrated in the submitted code.

To resolve this issue, consider using file_get_contents(), which reads the entire file into a string. You can then perform the search for the specified string using strpos() within this string. Here's an optimized code snippet:

<code class="php"><?php
    if( strpos(file_get_contents("./uuids.txt"), $_GET['id']) !== false) {
        // do stuff
    }
?></code>

Alternatively, if memory consumption is a concern, you could employ grep with exec():

<code class="php"><?php
    if( exec('grep '.escapeshellarg($_GET['id']).' ./uuids.txt')) {
        // do stuff
    }
?></code>

The above is the detailed content of How to Determine if a File Contains a Specific String in 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