How to search file in folder by using php?

落花浮王杯 提交于 2020-01-05 07:32:03

问题


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?


回答1:


Use loop foreach and strpos function:

$files = scandir('allfiles');
foreach ($files as $file) {
    if (strpos('to-dlkkl', $file) !== false) {
         //file found
    }
}



回答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
    }
}



回答3:


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);
}

?>



回答4:


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 );


来源:https://stackoverflow.com/questions/48444521/how-to-search-file-in-folder-by-using-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!