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

DDD
Release: 2024-10-23 19:39:02
Original
907 people have browsed it

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

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

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!

source:php
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!