-1

I am a newbie to php and I would like to create php search apps.

My Follow code

  <?php 
    $html = file_get_contents("folder/one.html");
    if (strpos($html, "searchtext") !== false) {
      echo "found";
    } else {
      echo "not found";
    }
    ?>

Is it possible to search for multiple files???

My hard code method

<?php 
        $url1 = "folder/one.html";
        $html1 = file_get_contents($url1);
        if (strpos($html1, "searchtext") !== false) {
          echo "found it from folder/one.html";
        } 
    
        $url2 = "folder/two.html";
        $html2 = file_get_contents($url2);
        if (strpos($html2, "searchtext") !== false) {
          echo "found it from folder/two.html";
        } 
  
       ......loop
    
        $url9999 = "folder/ninethousandninehundredninety-nine.html";
        $html9999 = file_get_contents($url9999);
        if (strpos($html9999, "searchtext") !== false) {
          echo "found it from folder/ninethousandninehundredninety-nine.html";
        } 
        ?>

anyidea how to use file_get_contents() to search multiple files? Thank you very much

MaryAnn
  • 95
  • 1
  • 8
  • 1
    You might want to start by exploring the option to [iterate all the files in a folder](https://stackoverflow.com/questions/4202175/php-script-to-loop-through-all-of-the-files-in-a-directory) and then perform the search on each of the files. – El_Vanja Jan 14 '21 at 13:22
  • Assuming your hard-coded method works, there is rather little point in asking “is it possible”. So, what would be your _actual_ question then? How to improve this? Well you could for example put all the file names into an array, and then loop over that. (If all the files are named _exactly_ as written-out-English-number, then you could perhaps also use a simple for loop, and combine it with a little script snippet that can write out those numbers in that form.) – CBroe Jan 14 '21 at 13:23

1 Answers1

2

Assuming that all the files are in the same directory, you can do something like this:

<?php 
    foreach ( glob("folder/*.html") as $filename) {
        $html = file_get_contents($filename);
        if (strpos($html, "searchtext") !== false) {
            print_r("Result found in $filename \r\n");
        }
    }
?>

This is not a particularly efficient way of looking for text in a file, and it will probably fail if you're looking for anything that might be multi-byte encoded, but it will do the job.

matigo
  • 1,321
  • 1
  • 6
  • 16