我不确定如何编写代码来搜索文件夹中的文件。我有以下代码来查看文件夹调用“文件”中的所有文件。
文件示例
abc-def.txt
ghi-jkl.txt
所以我希望有一个输入,如果我输入像abc所以它将搜索所有文件中有abc并显示出来。有可能吗?
$thelist = "";
if ($handle = opendir('./files/')) {
while (false !== ($file = readdir($handle))){
if ($file != "." && $file != ".."){
$thelist .= $file . '<br>';
}
}
closedir($handle);
}
echo $thelist;
unset($thelist);
我需要帮助。
答案 0 :(得分:0)
按模式搜索有一个很好的函数glob:
$pattern = filter_input(INPUT_POST, 'pattern', "*.txt", FILTER_SANITIZE_STRING);
foreach (glob($pattern) as $filename) {
echo "$filename \n";
}
答案 1 :(得分:0)
这是我的教学示例
<?php // demo/find_matching_files.php
/**
* Put this script in the web root or other high-level directory
*
* Traverse this directory and all sub-directories down the tree
* Show the matching files
*
* http://php.net/manual/en/class.recursivedirectoryiterator.php#85805
*/
error_reporting( E_ALL );
// USE THE OUTPUT BUFFER TO COLLECT THE LIST OF FILES
ob_start();
// USE THE REQUEST VARIABLE TO MATCH A SUBSTRING OF THE FILE NAME
$q = !empty($_GET['q']) ? $_GET['q'] : NULL;
if (empty($q)) trigger_error('Missing URL request argument "q=" for file name', E_USER_ERROR);
// CONSTRUCT THE REGEX
$rgx
= '#' // REGEX DELIMITER
. preg_quote($q)
. '#' // REGEX DELIMITER
. 'i' // CASE-INSENSITIVE
;
// START IN THE CURRENT DIRECTORY
$path = realpath(getcwd());
// COLLECT THE DIRECTORY INFORMATION OBJECTS
$objs = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST);
// ITERATE OVER THE OBJECTS
foreach($objs as $name => $obj)
{
if (preg_match($rgx, $name)) echo PHP_EOL . $name;
}
// IF THERE ARE MATCHES OR NO MATCHES
$out = ob_get_clean();
echo '<pre>';
if (empty($out))
{
echo PHP_EOL . "No match found for <b>$q</b>.";
}
else
{
echo PHP_EOL . "Matches for <b>$q</b>.";
}
// SHOW THE GIT BRANCH
$root = '.git/HEAD';
$text = @file_get_contents($root);
if ($text)
{
$text = explode(DIRECTORY_SEPARATOR, $text);
$text = array_slice($text, 2);
$name = implode(DIRECTORY_SEPARATOR, $text);
echo PHP_EOL . "On Git branch: $name" . PHP_EOL;
}
else
{
echo PHP_EOL . "On Git branch: UNKNOWN" . PHP_EOL;
}
// SHOW THE MATCHES
echo $out;
答案 2 :(得分:-1)