5

I have a folder called allfiles, and there are some files in this folder, such as

 1212-how-to-sddk-thosd.html
 3454-go-to-dlkkl-sdf.html
 0987-sfda-asf-fdf-12331.html
 4789-how-to-fdaaf-65536.html

I use scandir to list all files, and now I need to find the file by with keywords, example to-dlkkl is the keyword, and I will get the file 3454-go-to-dlkkl-sdf.html.

Glob seems not work, and opendir and readdir are not work well, any ideas?

  • What did you try for `glob`? I'm thinking that you'll need something like this: `glob("/path/to/allfiles/*to-dlkkl*")` – Ben Harris Jan 25 '18 at 13:54

4 Answers4

10

Use loop foreach and strpos function:

$files = scandir('allfiles');
foreach ($files as $file) {
    if (strpos('to-dlkkl', $file) !== false) {
         //file found
    }
}
Vladimir
  • 1,373
  • 8
  • 12
3

I wonder why glob() function not working for it?

The below code should work I guess,

$existing_dir = getcwd();
// path to dir
chdir( '/var/www/allfiles/' );

foreach( glob( '*to-dlkkl*.html' ) as $html_file ) {
    echo $html_file . '<br />';
}

chdir( $existing_dir );
2

you can use strstr to get actual file

$allfiles = scandir('./');
foreach ($allfiles as $file) {
    if (strstr($file, 'to-dlkkl')) {
        echo "file found"; //do what you want
    }
}
Soubhagya Kumar Barik
  • 1,979
  • 20
  • 26
0

If You want to search specific file under directory then you can use preg_match() .

<?php
  if ($handle = opendir('/var/www/html/j')) { // here add your directory
  $keyword = "index.php"; // your keyword
    while (false !== ($entry = readdir($handle))) {
        // (preg_match('/\.txt$/', $entry)) {
        if (preg_match('/'.$keyword.'/i', $entry)) {
            echo "$entry\n";
        }
    }

    closedir($handle);
}

?>
prakash tank
  • 1,269
  • 1
  • 9
  • 15