phpsearchscandir

php scandir for given $q search query


i have search values like "search value" (defined as $q) and .txt files called "search value.txt" in /mydir/ directory. How can i scandir /mydir/ for the search value ($q) and put the found .txt file with php include command into page? Or is it a better way to put $q value into php file_get_contents php code (i mean put them together like a txt filename like (q$.txt - searchvalue.txt somehow) and pull the content of the .txt file into page? If yes, how? Thanks in advance.


Solution

  • Suppose you have this directory structure :

    mydir
      --file1.tx
      --file2.tx
    index.php
    

    index.php

    $filepath = glob("mydir/*.txt");//read all txt files in data directory
    //print_r($filepath);//debug purpose
    $search = 'file1';
    
    // Browse all files and search the $search string in filenames
    foreach ($filepath as $filename) {
    
        // Give us file name only without the extension
        $fileNameOnly = basename($filename, '.txt');
    
        // Check if a file name only contains exactly our keyword $search
        $isExactMatch = preg_match("/\b".$search."\b/iu", $fileNameOnly);
    
        if ( $isExactMatch ) {
          // Include the .txt file as result
          require $filename;
        }
    }
    

    Tested, it does the trick.